Cheap VPS & Xen Server


Residential Proxy Network - Hourly & Monthly Packages

PHP Recursive Function


PHP also supports recursive function call like C/C++. In such case, we call current function within 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 script.

Example 1: Printing number

  1. <?php
  2. function display($number) {
  3.     if($number<=5){
  4.      echo “$number <br/>”;
  5.      display($number+1);
  6.     }
  7. }
  8. display(1);
  9. ?>

Output:

1
2
3
4
5

Example 2 : Factorial Number

  1. <?php
  2. function factorial($n)
  3. {
  4.     if ($n < 0)
  5.         return -1; /*Wrong value*/
  6.     if ($n == 0)
  7.         return 1; /*Terminating condition*/
  8.     return ($n * factorial ($n -1));
  9. }
  10. echo factorial(5);
  11. ?>

Output:

120

Comments

comments