Home > Backend Development > PHP Problem > PHP recursive function usage

PHP recursive function usage

Guanhui
Release: 2023-03-01 12:46:01
Original
2396 people have browsed it

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

<?php
 //声明一个函数,用于测试递归
 function test($n){
   echo $n." ";        //在函数开始输出参数的值
   if($n>0){                //判断参数是否大于0
     test($n-1);            //如果参数大于0则调用自己,并将参数减1后再次传入
   }else{                   //判断参数是不大于0
     echo "<-------->  ";
   }
   echo $n." ";
 }
 test(10);                   //调用test函数将整数10传给参数
?>
Copy after login

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
Copy after login

, 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 "<-->", 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
Copy after login
# 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!

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template