How to Increment / Decrement a Number with PHP

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

Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.


If you found this article helpful, please consider buying me a coffee.