Recursive function in php

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

So i give the simplest example of factorial using recursive function .so let me introduce about factorial first


Factorials are a very easy maths concept. They are written like 5! and this means  5*4*3*2*1. So  6! is 720 and  4! is 24.

    function factorial($number) { 

         if ($number < 2) { 
             return 1; 
         } else { 
            return ($number * factorial($number-1)); 
     // call to factorial function....
      $result = factorial(6); 
      echo "factorial of 6 is :".$result;

You can call factorial(6) for example, and it will first of all figure out that it should jump into the else clause. However this causes a call to factorial so PHP will go to work that out and realise that it needs to call the function again … and so on. When ($number-1) eventually gets small enough, we’ll return a 1 rather than calling the function again, and each of the nested function calls will find its return value and return. When we call the factorial function outside the function then it will return a value that will we the result and finally we print it on the screen.

0 0 vote
Article Rating

Do you want to hire us for your Project Work? Then Contact US.
Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x