PHP recursion example.

In this article, we are going to show you how to create a recursive function in PHP.

A recursive function is a function that calls itself. However, you must be careful, as your code should only carry out a certain number of recursive function calls.

In other words, there must be a mechanism that stops the recursion after you’ve reached the desired result. For example, you might use an IF statement.

If you allow your function to carry out an unlimited number of calls, you could receive the following error:

“Fatal error: Maximum function nesting level of ‘100’ reached, aborting!”

That, or your PHP script will run into memory issues.

Let’s take a look at an example of a recursive function in PHP:

//Our recursive function.
function recursive($num){
    //Print out the number.
    echo $num, '<br>';
    //If the number is less or equal to 50.
    if($num < 50){
        //Call the function again. Increment number by one.
        return recursive($num + 1);
    }
}

//Set our start number to 1.
$startNum = 1;

//Call our recursive function.
recursive($startNum);

The code above is pretty simple.

Basically, the function checks to see if the number ($num) is less than 50.

If the number is less than 50, we increment the number and call the function again.

This process will then repeat itself until $num reaches 50.

If you are using Xdebug and you need to go deeper than 100 levels, then you will need to increase the xdebug.max_nesting_level setting.

You can do this by using the ini_set function:

//Increase the max nesting level.
ini_set('xdebug.max_nesting_level', 150);

It is important to note that going through 100 levels of recursion is probably a pretty bad idea.

If you are reaching this level, then you should probably think about using a different solution.

If you’re looking for more examples, you can check out our article on how to print out a PHP array with recursion.