Recursive Function In PHP
PHP also supports recursive function call like C/C++. In such a case, we call the current function within a function. It is also known as recursion.
It is recommended to avoid recursive function call over 200 recursion level because it may smash the stack and may cause the termination of the script.
How to write a recursive function in PHP
In general terms, a recursive function works like this:
- The calling code calls the recursive function.
- The function does any processing or calculations required.
- If the base case has not yet been reached, the function calls itself to continue the recursion. This creates a new instance of the function.
- If the base case is reached, the function just returns control to the code that called it, thereby ending the recursion.
In pseudocode, a simple recursive function looks something like this:
Syntax
function myRecursiveFunction() {
// (do the required processing...)
if ( baseCaseReached ) {
// end the recursion
return;
} else {
// continue the recursion
myRecursiveFunction();
}
Example 1: Printing number
<?php
function myDisplay($number) {
if($number<=5){
echo "$number <br/>";
myDisplay($number+1);
}
}
myDisplay(1);
?>
Output:
1
2
3
4
5
Example 2: Factorial Number
<?php
function factorialCal($n)
{
if ($n < 0)
return -1; /*Wrong value*/
if ($n == 0)
return 1; /*Terminating condition*/
return ($n * factorialCal($n -1));
}
echo factorialCal(5);
?>
Output:
120
Series:
PHP Tutorials Hub
