We introduced in the previous article on the PHP recursive function of the return value problem, then we will introduce you to the next one on the PHP recursive function of a logic problem, this problem a lot of small partners would appear, today take everyone to parse!
First of all, we need to know what the recursive function is, and in layman's terms it is the function that calls itself.
Now you need to design a piece of code to solve the 1 to 10 overlay problem.
Code A:
<?php//recursive function $num=10;function Add ($sum) {static $tot, if ($sum >=1) {$tot + = $sum; Add (--$sum);} Else{return $tot;}} echo Add ($num);? >
Code B:
<?php//recursive function $num=10;function Add ($sum) {static $tot, if ($sum >=1) {$tot + = $sum; return Add (--$sum);} Else{return $tot;}} echo Add ($num);? >
A does not print the desired results, B can be achieved. The only difference in A and B code is the addition of a return in the IF.
The following is the beginning of the analysis of the entire recursive process, it is entirely possible to see the inception of the dream space to deepen understanding: (in the case of a code can not be implemented as an example)
1. Take 10 into the function, and after the IF statement is judged, $tot begin stacking.
2. Here's the point: take the parameter minus one and bring it back into the function. (No return value!!!) )
3. The above process has been circulating until the $sum=1, which is from the outside to the inside, from 10 to 1, and the 10-layer loop has no return value.
4. When $sum =0, a return value is required.
It's like, in the Dream space, the protagonist wakes up in a 11-story dream, but the first 10-story dreams are in the sleep phase. This protagonist you feel awake come over, obviously impossible. He can only be stuck on the 11th floor of the dream, never wake up.
The only way to get the protagonist to wake up is to wake up and come back to real life. In contrast to the a code, the B code requires a return value starting from the first layer, and a return value to 11 levels. So 11 layer woke up after the activation of the 10th layer, and then a layer of activation, and finally came to a smooth wake up, the final result is the correct output.
Summarize:
Through the above PHP recursive function in the logic problem, many small partners may feel the same as their own encounter, hope that through the above two code to help you solve your problem!
Related recommendations:
Resolution of return value problem in PHP recursive function
Analysis of three ways to implement PHP recursive function
Example of using PHP recursive functions
How does php recursive function work? Typical examples of PHP recursive functions