Welcome to WebmasterWorld Guest from 18.208.186.19

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

Why this decrement operator?

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

Senior Member

WebmasterWorld Senior Member 10+ Year Member

joined:June 6, 2004
posts: 2239
votes: 0


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--;
}
?>
11:19 am on July 20, 2015 (gmt 0)

Full Member

Top Contributors Of The Month

joined:Apr 11, 2015
posts: 328
votes: 24


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);
}
}
2:15 pm on July 20, 2015 (gmt 0)

Senior Member

WebmasterWorld Senior Member 10+ Year Member

joined:June 6, 2004
posts: 2239
votes: 0


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