Incrementing / Decrementing a Number by a Number with PHP

We’ve previously discussed how to simply increment and decrement a variable but that only covered incrementing by a value of 1. What about when you want to increment a variable by 5s? There’s a few different ways this can be accomplished. First, the obvious (albeit far from ideal) using ++ 5 times:

$i = 0

$i++
$i++
$i++
$i++
$i++

echo $i // 5!

I know, that’s silly, but I’m sure someone out there has done it before. Now let’s get serious, to increment a variable by 5 you can use +=, which is similar to ++ but allows you specify the value to increment by:

$i  = 0
$i += 5

echo $i // Still 5!

Decrementing works in quite the same way but, you guessed it, uses -= instead:

$i  = 10
$i -= 5

echo $i // 5, yet again!

The use of += and -= is the shorthand equivalent of the following syntax:

$i = $i + 5
$j = $j - 5

If you ever run into (or already have run into) the first example of multiple ++ or --s please please please leave a comment below!

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.