PHP Functions Arguments


What is function in PHP ?

A function is a block of code that execute a assigned task. function will executed by call to function

There are two types of functions

  • Built-in Functions
  • User Defined Functions

PHP Built-in Functions

PHP has great collection of internal or built-in functions that you can use directly. Example : var_dump(),print_r(),trim(),strlen(),ucfirst() etc

PHP User Defined Functions

A User-defined function is defined by user, user can create own function to use for code reusablity

Benefits of Using Functions

  1. Code reusability, same function can use multiple times just need to call it
  2. Easy to understand, user can break large program into some functions
  3. Modularity to your program's structure

Example : User-defined functions

Function declaration consists of mainly 3 parts

  • returntype
  • function name
  • parameter list
//displayFullName is function name
//$fname and $lname are the parameters
function displayFullName($fname,$lname)
{
	$fullname= $fname.' '.$lname; //function defintion
	return $fullname;
}

//Call the funtion
//Vipin and Kumar are the arguments
echo displayFullName('Vipin','Kumar');
//Output :: Vipin Kumar	
Note: Function name are case-insensitive. Function name should be start with a letter or an underscore.

Functions within functions in PHP

As per example, we can not call the directly inner function(test2), First you need to call the test1 function.

function test1()
{
	echo 'ABC';
	function test2()
	{
		echo 'XYZ';
	}
}

/* You can not call test2() yet since it doesn't exist. */   
test1(); // ABC

/* Now you can call test2() it's available now. */   
test2(); // XYZ 
Note: All functions and classes have the global scope in PHP, directly can call in any scope.

Recursive functions in PHP

A function can call recursive in PHP, if recursion function is called infinite then PHP program will show error after call some recursion levels

function recursion_php($n)
{
	if($n<=10)
	{
		echo $n;
		$n++;
		recursion_php($n);
	}
}
recursion_php(1); // 1 2 3 4 5 6 7 8 9 10