Skip to Main Content
PHP in a Nutshell
book

PHP in a Nutshell

by Paul Hudson
October 2005
Intermediate to advanced content levelIntermediate to advanced
372 pages
11h 35m
English
O'Reilly Media, Inc.
Content preview from PHP in a Nutshell

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.

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe
Learning PHP

Learning PHP

David Sklar

Publisher Resources

ISBN: 0596100671Errata Page