Incrementing and decrementing a variable can be accomplished with C-style pre- and post-operators. The pre-operators return the value after it as been incremented or decremented, post- return the value before. Let’s take a look at incrementing first:
$i = 1
echo ++$i // outputs 2
echo $i++ // also outputs 2
echo $i // outputs 3
You can pick either the pre- or post-operator based on whether you want to interact with the value of the variable before or after it’s been operated on. To decrement, just swap the ++
for --
:
$i = 10
echo --$i // outputs 9
echo $i-- // also outputs 9
echo $i // outputs 8
In a future post I’ll be discussing incrementing and decrementing by a value other than 1 and also applying the same logic to a string O_o