PHP Recursive Function PHP

PHP Recursive Function  

PHP Recursive Function

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.     
  9. display(1);    
  10. ?>    

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.     
  11. echo factorial(5);    
  12. ?>    

Output:

120
 

Download free E-book of PHP


#askProgrammers
Learn Programming for Free


Join Programmers Community on Telegram


Talk with Experienced Programmers


Just drop a message, we will solve your queries