Skip to content
Advertisement

Mutiple consecutive outputs instead of one in a function in PHP

I am learning about static variables in PHP and came across this code in PHP manual.

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

    $count++;
    echo $count;
    if ($count < 10) {
        test();
    }
    $count--;
}
?>

I couldn’t understand the purpose of last $count--;. So, I wrote a different version of the function below:

<?php

function test() {
    static $count = 0;

    $count++;

    echo $count;
    if ($count < 10) {
        test();
    }
    echo 'I am here!';

    $count--;
}

test();
?>

The output of above code is:

12345678910I am here!I am here!I am here!I am here!I am here!I am here!I am here!I am here!I am here!I am here!

Why isn’t the output just the line below because we go past the if condition only once.

12345678910I am here!

If we are going past the if condition multiple times, then shouldn’t the output be:

1I am here!2I am here!3I am here!4I am here!5I am here!6I am here!7I am here!8I am here!9I am here!10I am here!

Thanks.

Advertisement

Answer

This is more about recursion than static variables. However:

Why the numbers are written out first and the text afterwards? Let’s break each run of the function. For simplification, I’ll only use example with 2 calls (if ($count < 2))

  • 1st call starts, $count is incremented to 1
    • prints 1
  • Within the 1st call, the condition $count < 2 is met, so it calls test() (so that’s going to be the 2nd call)
  • 2nd call starts, $count is incremented to 2 (if it weren’t static, it wouldn’t keep the value from the higher scope)
    • prints 2
  • Within the 2nd call, the condition $count < 2 is NOT met, so it skips the if block
    • prints I am here! and ends the 2nd call
  • Now the 1st call is done running the recursive function so it continues
    • prints I am here! and ends the 1st call
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement