PHP - Recursive Function

PHP also supports recursive function call like C/C++. In such case, we call current function within function. It is also known as recursion.

 In simple words, recursive function means we can call a PHP function within another function without any argument.

It is recommended to avoid recursive function call over 200 recursion level because it may smash the stack and may cause the termination of script.

Example 1: Printing number

<?php    

function display($number) {    

    if($number<=5){    

     echo "$number <br/>";    

     display($number+1);    

    }  

}    

display(1);    

?>

Output:

1

2

3

4

5

Example 2 : Factorial Number

<?php    

function factorial($n)    

{    

    if ($n < 0)    

        return -1; /*Wrong value*/    

    if ($n == 0)    

        return 1; /*Terminating condition*/    

    return ($n * factorial ($n -1));    

}    

echo factorial(5);    

?> 

Output:

120