Incrementing and Decrementing Operators
The next two operators do different things, depending on where you place them. The difference is explained in Table 6-6.
Table 6-6. The incrementing and decrementing operators
|
++$a |
Pre-increment |
Increments |
|
$a++ |
Post-increment |
Returns |
|
—$a |
Pre-decrement |
Decrements |
|
$a— |
Post-decrement |
Returns |
The incrementing and decrementing operators can be placed either before or after a variable, and the effect is different depending on where the operator is placed. Here's a code example:
$foo = 5;
$bar = $foo++;
print "Foo is $foo\n";
print "Bar is $bar\n";That will output the following:
Foo is 6
Bar is 5The reason behind this is that ++, when placed after a variable, is the post-increment operator, which immediately returns the original value of the variable before incrementing it. In line 2 of our script, the value of $foo (5) is returned and stored in $bar, then
$foo is incremented by one. If we had put the ++ before $foo rather than after it, $foo would have been incremented then returned, which would have made both $foo and $bar 6.