PHP recursion example.

A recursive function is a function that calls itself. Care must be taken in PHP, however, as your code must not carry out a certain number of recursive function calls. i.e. There must be a mechanism (IF statement, etc) that stops the recursion after the desired result has been found. If you allow your function to carry out an unlimited amount of calls (and you have XDebug installed), you will receive the error: “Fatal error: Maximum function nesting level of ‘100’ reached, aborting!”

Lets take a look at a simple 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.

The code above is pretty simple. Basically, the function checks to see if the number is less than 50. If the number is less than 50, then we increment the number and call the function again. This process is repeated until the number has reached 50.

Note that if you need to go deeper than 100 levels, then you will need to increase the xdebug.max_nesting_level setting. You can do this via the ini_set function if you’re on a hosted platform that allows you to modify PHP ini settings on the fly:


ini_set('xdebug.max_nesting_level', 150);

It is worth noting that going over 100 levels of recursion is probably a pretty bad idea! If you are reaching this level, then recursion is probably not the solution that you need!

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