PHP User-Defined Functions

A function is lines of code which takes some parameters and execute on called and return some value. This is built-in PHP functions but We can define our own function in PHP and use it anywhere in our code. It is useful to reuse some lines of code in our project.

User-Defined Functions

  • In PHP, we can define our own functions which are called user-defined functions.
  • A function is executed when it is called, not when it is defined.

Few Rules to define Functions

  • A function name must contain alphabets, numbers and underscores. No other special character is allowed.
  • The function name should start with either an alphabet or an underscore and it should not start with a number.
  • Function names are case-insensitive and should not contain space.
  • Function names can accept parameters and can also return values.

Syntax:-

<?php
	function functionname(arguments){
		//block of code
	}
?>

There are four types of function:-

  • Function without argument without a return value.
  • Function with the argument without a return value.
  • Function without argument with a return value.
  • Function with an argument with a return value.

Function without argument without return value:-

<?php
	function add()
	{
		$a=10;
		$b=20;
		$c= $a + $b;
		echo "add = $c"; 
	}
	add();
?>

Output:-

30

Function with argument without return value:-

<?php
	function add( $a, $b)
	{
		$c= $a + $b;
		echo ā€œ add = $cā€; 
	}
	add(10, 20);
?>

Output:-

30

Function without argument with return value:-

<?php
	function add()
	{
		$a=10;
		$b=20;
		$c= $a + $b;
		return $c;
	}
	echo  "add = ". add(); 
?>

Output:-

30

Function with argument with return value:-

<?php
	function add( $a, $b)
	{
		$c= $a + $b;
		return $c;
	}
	echo ā€œ add = ā€. add(10, 20); 
?>

Output:-

30

Function with default argument:-

  • In PHP, you can define function having default argument. So, if you do not pass the value for that argument it will consider default value for that argument.
  • But if you pass an explicit value for that argument it will override the default value.

Example

<?php
	function show( $a, $b = 10)
	{
		echo "a= $a </br>"; 
		echo "b= $b </br>";
	}
	show(70);
	show(100, 200);
?>

Output:-

a= 70
a= 10
a= 100
b= 200