Home > Article > Backend Development > Application of PHP recursive algorithm (with examples)
Application of PHP recursive algorithm
The recursive function is a self-calling function, directly or directly in the function body Call yourself, but you need to set the conditions for self-calling. If the conditions are met, call the function itself. If not, stop the self-calling of this function, and then return the control of the current process to the upper layer function for execution. Maybe it is still difficult to understand after explaining it to us, such as:
Example:
function test ($n){ echo $n." "; if($n>0){ test($n-1); }else{ echo ""; } echo $n." "; } test(2) 这个比如终究的输出结果是2 1 0<–>0 1 2
I will explainwhy the output is like this
① Execute test(2), echo 2, and then because 2>0, execute test(1), followed by echo 2 that has not had time to execute
② Execute test(1), echo 1, and then because 1>0, execute test(0). Similarly, there is echo 1 that has not had time to execute
③ Execute test(0), echo 0, execute test(0), echo 0, now the condition of 0>0 is not satisfied, the test() function is not executed, but echo "", and the following echo 0 is executed, now The function no longer calls itself, and begins to return the control of the process to the upper layer function for execution, that is, it begins to execute the last echo that has not been output by all the test() functions just now. The level 0 is 1 means output 1. The upper layer of 1 is 2, which means output 2. 2 does not have a layer, so the output content is 2 1 05fb6f3beb31540706eb26a1cd1069f9d0 1 2
Thank you for your patience. Read it, I hope you all benefit from it.
Recommended tutorial: "PHP Tutorial"
The above is the detailed content of Application of PHP recursive algorithm (with examples). For more information, please follow other related articles on the PHP Chinese website!