In this tutorial, you will learn about PHP Recursive Function.

What is Recursive Function?

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

Syntax:

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

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

Example:

It will display 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

Leave a Reply

Your email address will not be published. Required fields are marked *