Search code examples
phpfunctionrecursionstaticstatic-variables

How many times the last statement of a recursive function block gets executed?


Consider the below code snippet demonstrating recursion :

<?php
  function test() {
    static $count = 0;

    $count++;
    echo $count."<br>";
    if($count < 10) {
      test();
    }
    echo "Count Value : ".$count--;
  }

  test();
?>

Output of above code is as below :

1
2
3
4
5
6
7
8
9
10
Count Value : 10
Count Value : 9
Count Value : 8
Count Value : 7
Count Value : 6
Count Value : 5
Count Value : 4
Count Value : 3
Count Value : 2
Count Value : 1

I expected the last code statement of the function test() i.e. echo "Count Value : ".$count--; will get execute only once when the if condition returns false upon $count = 10; and everything would be finish.

But unexpectedly, I'm getting it executed ten times with decreasing value of variable $count. I'm not understanding how it's happening? How is the code flow getting manipulated here unexpectedly?

As the recursive function call is made inside the if condition how can it get called subsequently for 10 more times even after failing the if condition?

Please explain me.

Note : I haven't forgot to add else and I don't want it. Just explain why and how the last statement is getting executed only after printing nos. from 1 to 10 and only after the failing of if condition. When the if condition was returning true it was not getting executed. How?


Solution

  • I think you forgot the else.

    <?php
      function test() {
        static $count = 0;
    
        $count++;
        echo $count."<br>";
        if($count < 10) {
          test(); // when this call is made, all the code bellow waits for it to return
        } else {
          echo "Count Value : ".$count--;
        }
      }
    
      test();
    ?>
    

    What happens is that every time you call test(), inside the if condition, the execution stops until the newly called test() returns. The test() function only returns when $count >= 10. which means that all hanging functions call will continue. What is a RECURSIVE Function in PHP?

    Your code can be translated to something like this;

    <?php
      function test() {
        static $count = 0;
    
        $count++;
        echo $count."<br>";
        if($count < 10) {
    
          static $count = 1;
    
          $count++;
          echo $count."<br>";
          if($count < 10) {
    
            static $count = 2;
    
            $count++;
            echo $count."<br>";
            if($count < 10) {
    
    
              // ... the code repeats until the point when $count = 9
    
            } else {
              echo "Count Value : ".$count--;
            }
    
          } else {
            echo "Count Value : ".$count--;
          }
    
    
        } else {
          echo "Count Value : ".$count--;
        }
      }
    
      test();
    ?>