How to Increment / Decrement a Number with PHP

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

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. Born again Linux user. Founder of Holiday API, and author of the best damn Lorem Ipsum Library for PHP.

Currently Reading

Slobberknocker: My Life in Wrestling
The 4-Hour Workweek, Expanded and Updated

Previous Reads

Buy Me a Coffee Become a Sponsor

Related Articles