PHP Recursive functions

      No Comments on PHP Recursive functions

PHP Recursive functions are the functions which call themselves.

PHP Recursive functions are considered useful, as they break complex problems into simple cases, and solve a problem by reiterating those simple cases.

Most basic PHP Recursive functions

Let us begin with calculating factorial of a number using recursion:

<?php 
  function fact($x)
  {
     if($x==1)
       return 1;
     else
     {
       return $x*fact($x-1);
     }
  }
  echo fact(4);
?>

The statement echo(4); calls the function fact. the value 4 gets assigned to $x. The program functions as :

$x=4;
function fact(4)
{
  if($x==1)
    return 1; // is not true as $x=4;
  else
    return 4*fact(4-1); //recursive call to fact(3);
}
$x=3;
function fact(3)
{
  if($x==1)
    return 1; // is not true as $x=3;
  else
    return 3*fact(3-1); //recursive call to fact(2);
}
$x=2;
function fact(2)
{
  if($x==1)
    return 1; // is not true as $x=2;
  else
    return 2*fact(2-1); //recursive call to fact(1);
}
$x=1;
function fact(1)
{
  if($x==1)
    return 1; // is true - 1 is returned
}

Output: 24

Another example:

<?php 
 function num($s)
 {
    echo $s;
   if($s<50)
    {
       $s++;
       num($s);
    }
 }
?>

Leave a Reply

Your email address will not be published. Required fields are marked *