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.
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)
Thank you very much for the clear explanation, whitespace. Makes complete sense.