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:
In pseudocode, a simple recursive function looks something like this:
function myRecursiveFunction() {
// (do the required processing...)
if ( baseCaseReached ) {
// end the recursion
return;
} else {
// continue the recursion
myRecursiveFunction();
}
<?php
function myDisplay($number) {
if($number<=5){
echo "$number <br/>";
myDisplay($number+1);
}
}
myDisplay(1);
?>
Output:
1
2
3
4
5
<?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
© 2024 Easy To Learning. All Rights Reserved | Design by Easy To Learning