digui($i-1);            for($j=1;$j"/> digui($i-1);            for($j=1;$j">

Home  >  Article  >  Backend Development  >  PHP recursive function example analysis

PHP recursive function example analysis

小云云
小云云Original
2018-03-06 11:38:521789browse

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." ";
    }

Call $this->digui2(3);

Result

3 2 1 0 71fb34173e4ee87dab1f85dc1c283a440 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);
?>

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!

Statement:
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