PHP recursive function example analysis

小云云
Release: 2023-03-20 20:00:02
Original
1796 people have browsed it

This article

   public function digui($i)
    {

        if($i=='1'){
            echo  "*" ;
            echo "<br>";
            return ;
        }else{
            $this->digui($i-1);
            for($j=1;$j<=$i;$j++){
                echo  "*" ;
            }
            echo "<br>";
        }
    }
 调用 $this->digui(3);
结果
*
**
***

  function digui2($n){
        echo $n." ";
        if($n>0){
            $this-> digui2($n-1);
        }else{
            echo "<-->";
        }
        echo $n." ";
    }
Copy after login

Call $this->digui2(3);

Result

3 2 1 0 <-->0 1 2 3

Recursive function execution anatomy example (reposted from others)

Look at the following code:

<?php
function one($num){
echo $num;
two($num-1);
echo $num;
}
function two($num){
echo $num;
three($num-1);
echo $num;
}
function three($num){
echo $num;
}
one(3);
?>
Copy after login

The above code decomposes the test() function. We Thinking:
When executing the one(3) function, like the test() function, first output 3, and then call the two(2) function,
Note that the following 3 has not been output at this time,
Go on, execute the two(2) function, output 2, and call the three(1) function. Similarly, there is no time to output the following 2,
Execute three(1), output 1 directly, and no longer call other functions,
At this time, we wonder if the two() function just has not been executed yet. OK, then execute the unfinished part of the two() function. After the two() function is executed, the following 2 is output, and then starts Execute the unfinished part of the one() function, that is, output the following 3. At this time, all functions have been executed.
Then, the output result is:
3 2 1 2 3

Related recommendations:

Detailed explanation of php recursive function

Explanation on calling php recursive functions

Analysis of three ways to implement php recursive functions

The above is the detailed content of PHP recursive function example analysis. For more information, please follow other related articles on the PHP Chinese website!

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