Recursion means repeatedly calling a function to the same function.

The recursion function can be used up to the last element of any array

For Ex…

Print as many numbers as you need

function display ($startNum, $endNum)
{
    if($startNum <= $endNum){
        echo "$startNum <br/>";
        display($startNum + 1, $endNum);
    }
}

display(1, 50);

Note : Recursions have to give an end point to the function. If the end point is not defined then the function is called until the time of the script runs out or the memory is full.

For Ex…

If the condition in the above example is not used then the function continues to call that function.

function display($startNum, $endNum)
{
    echo "$startNum <br/>";
    display($startNum + 1, $endNum);
}

display(1, 50);

One accurate example of this would be searching through a report gadget. You may begin at the basis folder, after which you may search via all the files and folders within that one. After that, you will input every folder and seek via Interior of each folder.

Structure

It is counseled to avoid algorithmic call over two hundred formula level, as a result of that it's going to smash the stack and will cause the termination of script.

You can increase maximum nesting level limit with

ini_set ('xdebug.max_nesting_level', 1000);

Types Of Recursion :

1 .Indirect Recursion :

While a feature calls itself immediately, it is referred to as direct recursion. A function in a cycle of characteristic calls that finally invokes itself is referred to as indirect recursion.

In the indirect recursion function, the first function calls the second function and the second function calls the first function.

For ex...

function A($num) {
    $num -= 1;
    if($num > 0) {  
        echo "A is Calling B($num)n";
        $num = B($num);
    }
    return $num;
}

function B($num) {
    $num -= 2;
    if($num > 0) {
        echo "B is Calling A($num)n";
        $num = A($num);
    }
    return $num;
}

Output :-

Calling A(4)

A is Calling B(3)

B is Calling A(1)

Result : 0

2 .Head and Tail Recursion :

While referring to the examples above, we have been a user of Head Recursion. When the function calls itself, it waits for the end result from the call earlier than returning a value of its own. It’s possible to write functions in a way that they do not function on back values, but rather bypass all required values as parameters. This is known as “Tail Call” (or Tail Recursion). This method is normally desired as a Language’s Runtime and can occasionally optimize the calls so that there’s no chance of blowing up the call stack, but php does not try this.

For ex...

function factorial ($number, $factorial = 1) {
    if ($number < 0) {
        throw new InvalidArgumentException('Number cannot be less than zero (0)');
    }
    if ($number == 0) {
        return $factorial;
    }
    else {
        return factorial($number - 1, $factorial * $number);
    }
}