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 by one, then returns $a

$a++

Post-increment

Returns $a, then increments $a by one

—$a

Pre-decrement

Decrements $a by one, then returns $a

$a—

Post-decrement

Returns $a, then decrements $a by one

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 5

The 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.

Get PHP in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.