Forum Moderators: coopster

Message Too Old, No Replies

Why this decrement operator?

         

createErrorMsg

11:25 pm on Jul 12, 2015 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Could someone please clarify for me why this code snippet from the PHP manual includes a decrement operator after the if statement closes? The code seems to run the same with or without it.


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

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

whitespace

11:19 am on Jul 20, 2015 (gmt 0)

10+ Year Member Top Contributors Of The Month



The code seems to run the same with or without it.


Try calling the test() function more than once.

The $count-- statement is required in this example to reset the static $count variable between subsequent "external" calls (as opposed to internal recursive calls). This is assuming you always want the test() function to echo the numbers 1 to 10. If you remove the trailing decrement statement then subsequent calls will simply output the next single number. eg. 11, then 12, etc. The $count-- statement is executed when the recursive call returns, so ultimately resets the static $count variable back to 0 (zero) from 10.

It should be noted that this code snippet serves as an "example" of static variable behaviour (and to some extent recursive function calls). It's not necessarily a good real-world example to use a static variable in this way.

The above example can be rewritten to not use a static variable:

function test($count=0) {
$count++;
echo $count;
if ($count < 10) {
test($count);
}
}

createErrorMsg

2:15 pm on Jul 20, 2015 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Thank you very much for the clear explanation, whitespace. Makes complete sense.