PHP Recursive Function

A recursive function is a function that calls itself during its execution. PHP supports recursive function calls, by which we can call current function within function. It is also known as recursion. Lets see an example of it :
<?php
  function showNum($num) {
    if($num <= 10) {
      echo $num . "<br/>";
      $num++;
      showNum($num);
    }
  }

  showNum(1);

?>
Output :

1
2
3
4
5
6
7
8
9
10

At the above function showNum() function will call itself until the value of $num is less then or equal to 10. Now lets see another example for calculating factorial of given number :
<?php
  function factorial($num) {
    if($num == 0) {
      return 1;
    }
    return ($num * factorial($num - 1));
  }

  echo factorial(5);
?>
Output :

120


Next Topic :