Application of PHP recursive algorithm (with examples)

烟雨青岚
Release: 2023-04-08 19:44:01
forward
2426 people have browsed it

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

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 0<–>0 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!

Related labels:
source:csdn.net
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!