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
PHP has great collection of internal or built-in functions that you can use directly. Example : var_dump(),print_r(),trim(),strlen(),ucfirst() etc
A User-defined function is defined by user, user can create own function to use for code reusablity
Function declaration consists of mainly 3 parts
//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
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
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