Incrementing/decrementing operators are also shortcuts like +=
or -=
, and they only
work on variables. There are
four of them, and they need
special attention. We've already seen the first two:
++
: This operator on the left of the variable will increase the variable by 1, and then return the result. On the right, it will return the content of the variable, and after that increase it by 1.--
: This operator works the same as++
but decreases the value by 1 instead of increasing by 1.
Let's see an example:
<?php $a = 3; $b = $a++; // $b is 3, $a is 4 var_dump($a, $b); $b = ++$a; // $a and $b are 5 var_dump($a, $b);
In the preceding code, on the first assignment
to $b
, we use $a++
. The operator on the right will return first
the value of $a
, which is 3
, assign it to $b
, and
only then increase $a
by 1. In the
second assignment, the operator on the left first increases
$a
by 1, changes the value of
$a
to 5
, and
then assigns that value to $b
.