Home>Article>Backend Development> PHP recursive function usage
PHP recursive function usage
The recursive function is a self-calling function, which performs self-tuning directly or indirectly in the function body, but needs to be set to If the condition is met, the function itself will be called. If it is not met, the self-tuning of this function will be terminated, and then the control of the process will be returned to the upper layer function for execution.
Code example
0){ //判断参数是否大于0 test($n-1); //如果参数大于0则调用自己,并将参数减1后再次传入 }else{ //判断参数是不大于0 echo "<--------> "; } echo $n." "; } test(10); //调用test函数将整数10传给参数 ?>
First think about it, what is the final output of this example?
Okay, let’s take a look at the output result of this function: How about
10 9 8 7 6 5 4 3 2 1 0 <--> 0 1 2 3 4 5 6 7 8 9 10
, I wonder if this result is the same as expected?
Step explanation
The first step is to execute test(10), echo 10, and then because 10>0, execute test(9) , there is still echo 10 that has not had time to be executed. The second step is to execute test (9), echo 9, and then because 9>0, execute test (8). Similarly, there is still echo that has not had time to execute. 9
The third step is to execute test(8), echo 8, and then because 8>0, execute test(7). There is also echo 8 that has not had time to be executed.
Fourth step Step 1, execute test(7), echo 7, and then execute test(6) because 7>0, there is also echo 7
that has not been executed in time. Step 5, execute test(6), echo 6. Then because 6>0, test (5) is executed. There is also echo 6
#......
Step 10. , execute test(0), echo 0. At this time, the condition of 0>0 is not satisfied. The test() function is no longer executed, but echo "71fb34173e4ee87dab1f85dc1c283a44", and the subsequent echo 0
10 9 8 7 6 5 4 3 2 1 0 <--> 0 1 2 3 4 5 6 7 8 9 10# is executed. ##Recommended tutorial: "
PHP Tutorial"
The above is the detailed content of PHP recursive function usage. For more information, please follow other related articles on the PHP Chinese website!