• Tutorial List

PHP Recursive Function

Last updated May 15, 2020
PHP Recursive Function

What is Recursive Function?

When a function calls itself, it is called a recursive function.

Be careful when you create a recursive function as it can break your server or application.

Syntax:

<?php
  function myFunc(){ 
      myFunc();
  }
  myFunc();
?>

Example:

The following example displays numbers from 1 to 10. Read the following code and try to understand.

<?php
  function showNum($start,$end){
      //checking $start is less than or equal to $end
      if($start <= $end){
          // if $start is not equal to $end
          if($start !== $end){
              echo "$start<br>";
              showNum(++$start,$end);
          }
          else{
              echo $start;
          }

      }
      else{
          echo "Your Starting number is grater than ending number";
      }
  }

  showNum(1,10);
?>
Browser Output
1
2
3
4
5
6
7
8
9
10