PHP stops executing after a certain number of recursion loops

The problem I am facing is very strange. This happens when doing recursion loops. This does not happen when doing the same task for a loop or any other iteration.

Everything works when the function is called recursively ~ ~ 21,000 times. The problem arises when feeding this number.

My working code:

foo();

function foo($i = 1) {
    if ($i > 20000) {
         return;
    }
    echo $i . '<br/>';
    foo($i + 1);

    return;        
}

      

Outputs:


19998
19999
20000

The code doesn't work:   

foo();

function foo($i = 1) {
    if ($i > 30000) {  // Or any number above ~21000
         return;
    }
    echo $i . '<br/>';
    foo($i + 1);

    return;        
}

      

Results:


13493
13494
13

last line stops in the middle of the number. In some cases, it just sends an empty response to the server.

I am using apache2 server on Ubuntu with PHP version 5.6.10. Using Xampp, the same problem occurs, only the numbers are slightly different.

+3


source to share


1 answer


Most of the currently popular programming languages, including PHP, have a limit on how many functions a recursion function can execute. This is not a hard limit; depending on the state of your program, this could be a recursive call to tens of thousands of depths, or just a few deep. So it is not safe to implement deeply recursive functions like your example and your program will crash. See the note at the bottom of the PHP custom functions documentation:

Recursive function / method calls with more than 100-200 levels of recursion can break the stack and cause the current script to terminate.



Every time you call a function, the program must record where the execution was before the function started, so it knows where to start execution after the function returns. There is only limited space to store this information, so if you have too many function calls at the same time, you will run out of free space and your program will crash. This information, along with a bunch of other information, is stored on the stack, and when you run out of space on the stack, it is called a stack overflow or splits the stack.

Several languages ​​implement a feature known as tail call optimization , which allows unconstrained recursion under the right circumstances. Functional languages ​​often support this, such as Scheme and ML. However, PHP, as mentioned in Does PHP optimize tail recursion? ...

0


source







All Articles