Incrementing / Decrementing a Number by a Number with PHP

Josh Sherman
1 min read
Software Development 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!

Join the Conversation

Good stuff? Want more?

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

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.

Currently Reading

Parasie Eve

Previous Reads

Buy Me a Coffee Become a Sponsor

Related Articles