Home >>PHP Object Oriented >PHP Recursive Function

PHP Recursive Function

Recursive Function in PHP

Recursive function is a function which calls itself again and again until the termination condition arrive.

Create a recursive function to find factorial number

<?php
function fact($n)
{
if ($n === 0)
{ 
// our base case
return 1;
}
else 
{
return $n * fact($n-1); // <--calling itself.
}
}
echo fact(5);
?>
Output 120

In the above example there is a recursive function fact which call itself till the condition that is 1 (base case) arrive . The intermediate steps are stored in an stack. and the output is printed. The return value is based on an if condition. If the base value is not reached till then function calls itself with a decrement in text value of n as an argument. and if the base value arrived it is returned and the corresponding result gets displayed.


No Sidebar ads