Increment / Decrement Operators
What Are Increment and Decrement Operators? In simple terms: The increment operator ++ adds 1 to a variable, and the decrement operator -- subtracts 1. They are shortcuts for counting up and down. Tec
What Are Increment and Decrement Operators?
In simple terms: The increment operator ++ adds 1 to a variable, and the decrement operator -- subtracts 1. They are shortcuts for counting up and down.
Technically: ++ and -- are unary operators that modify a variable in place and return a value. Each has two forms — prefix (++$i) and postfix ($i++) — which differ in the value they return.
| Operator | Name | Effect | Returns |
|---|---|---|---|
++$a | Pre-increment | Adds 1 to $a | The new value |
$a++ | Post-increment | Adds 1 to $a | The old value |
--$a | Pre-decrement | Subtracts 1 from $a | The new value |
$a-- | Post-decrement | Subtracts 1 from $a | The old value |
Why They Exist
Counting by one is extremely common: loop counters, page views, retry attempts, item counts, positions in a list. $i++ is shorter than $i = $i + 1 or $i += 1, and it is instantly recognizable to developers from almost every C-style language.
Basic Usage
Example
<?php
$visitors = 0;
$visitors++;
$visitors++;
$visitors++;
echo "Visitors: $visitors\n";
$seatsLeft = 5;
$seatsLeft--;
echo "Seats left: $seatsLeft\n";
Output
Visitors: 3
Seats left: 4
When the operator is used as a standalone statement, the prefix and postfix forms behave identically: the variable changes by 1, and the returned value is ignored.
Prefix vs Postfix
The difference matters only when the result of the expression is used.
Example
<?php
$i = 5;
$a = $i++; // post-increment: $a gets the OLD value
echo "a = $a, i = $i\n";
$j = 5;
$b = ++$j; // pre-increment: $b gets the NEW value
echo "b = $b, j = $j\n";
$k = 5;
echo $k-- . "\n"; // prints 5, then $k becomes 4
echo --$k . "\n"; // $k becomes 3, prints 3
Output
a = 5, i = 6
b = 6, j = 6
5
3
Step by Step
| Statement | What Happens | Result |
|---|---|---|
$a = $i++ | Copy the current value (5) to $a, then increase $i | $a = 5, $i = 6 |
$b = ++$j | Increase $j to 6, then copy it to $b | $b = 6, $j = 6 |
echo $k-- | Print the current value (5), then decrease $k | prints 5, $k = 4 |
echo --$k | Decrease $k to 3, then print it | prints 3 |
A simple way to remember: the position of the operator tells you when the change happens relative to reading the value. Prefix: change first, then read. Postfix: read first, then change.
Using Increment in Loops
The most common use is the loop counter:
<?php
for ($i = 1; $i <= 5; $i++) {
echo "Lesson $i\n";
}
$countdown = 3;
while ($countdown > 0) {
echo "Starting in $countdown...\n";
$countdown--;
}
echo "Go!\n";
Output
Lesson 1
Lesson 2
Lesson 3
Lesson 4
Lesson 5
Starting in 3...
Starting in 2...
Starting in 1...
Go!
In the for loop's third part, the result of $i++ is not used, so $i++ and ++$i are equivalent. Loops are covered in For Loop and While Loop.
Using the Returned Value
Postfix increment is useful when you need the current position and then want to advance it:
<?php
$items = [];
$nextId = 101;
$items[$nextId++] = 'Keyboard';
$items[$nextId++] = 'Mouse';
$items[$nextId++] = 'Monitor';
print_r($items);
echo "Next ID will be: $nextId\n";
Output
Array
(
[101] => Keyboard
[102] => Mouse
[103] => Monitor
)
Next ID will be: 104
Each assignment uses the current ID as the key and then advances it. This is compact, but keep such expressions simple — combining several increments with other operations in one expression quickly becomes hard to read.
Counting Occurrences
<?php
$text = "the cat and the hat and the bat";
$counts = [];
foreach (explode(' ', $text) as $word) {
$counts[$word] ??= 0;
$counts[$word]++;
}
arsort($counts);
print_r($counts);
Output
Array
(
[the] => 3
[and] => 2
[cat] => 1
[hat] => 1
[bat] => 1
)
How It Works
explode(' ', $text)splits the sentence into words.$counts[$word] ??= 0creates the key with0the first time a word appears, avoiding an "Undefined array key" warning.$counts[$word]++increases that word's count.arsort()sorts by count in descending order while keeping the keys. (Words with equal counts keep their original order.)
PHP also offers array_count_values(), which does the same counting in one call: array_count_values(explode(' ', $text)).
Increment and Decrement With Different Types
++ and -- are designed for integers and floats. With other types, the behavior is inconsistent, which is why recent PHP versions warn about several cases.
| Value | ++ Result | -- Result |
|---|---|---|
5 (int) | 6 | 4 |
5.5 (float) | 6.5 | 4.5 |
"5" (numeric string) | int(6) | int(4) |
"5.5" (numeric string) | float(6.5) | float(4.5) |
null | int(1) | stays null (warning since PHP 8.3) |
true / false | unchanged (warning since PHP 8.3) | unchanged (warning since PHP 8.3) |
"a" (alphanumeric string) | "b" (see below) | unchanged |
PHP_INT_MAX | becomes a float | — |
Example
<?php
$fromForm = "7";
$fromForm++;
var_dump($fromForm);
$total = null;
$total++;
var_dump($total);
$price = 9.5;
$price--;
var_dump($price);
Output
int(8)
int(1)
float(8.5)
- A numeric string is converted to a number and then incremented.
- Incrementing
nullproduces1— but decrementingnullleaves it asnull. This asymmetry is a common surprise; since PHP 8.3, decrementingnullemits the warning "Decrement on type null has no effect, this will change in the next major version of PHP". - Incrementing or decrementing a boolean has no effect; since PHP 8.3 it emits a warning as well.
Rule: initialize counters with 0 (an integer) before using ++ or --.
Incrementing Letters: Alphanumeric Strings
For historical reasons, ++ on a non-numeric string follows Perl's "alphanumeric increment" rules:
<?php
$letter = 'a';
$letter++;
var_dump($letter);
$column = 'Z';
$column++;
var_dump($column);
$code = 'A9';
$code++;
var_dump($code);
Output (PHP 8.3 / 8.4)
string(1) "b"
string(2) "AA"
string(2) "B0"
The last character is advanced, and it "carries over" like a counter: Z becomes AA (similar to spreadsheet column names) and A9 becomes B0. -- does not reverse this; decrementing 'b' leaves it unchanged.
Because this behavior is surprising and inconsistent, PHP is phasing it out. PHP 8.3 added dedicated functions, and newer PHP versions deprecate using ++ on non-numeric strings:
<?php
var_dump(str_increment('Az'));
var_dump(str_increment('zz'));
var_dump(str_decrement('Ba'));
var_dump(str_decrement('aa'));
Output
string(2) "Ba"
string(3) "aaa"
string(2) "Az"
string(1) "z"
str_increment() and str_decrement() (PHP 8.3+) make the intent explicit, work symmetrically, and throw a ValueError for invalid input (for example, str_decrement('a') has no previous value).
Common Mistakes
Assigning a Post-Increment to the Same Variable
<?php
$i = 5;
$i = $i++;
var_dump($i);
Output
int(5)
$i++ returns the old value (5), increments $i to 6, and then the assignment overwrites $i with the returned 5. The increment is lost. Use either $i++; or $i = $i + 1; — never both.
Incrementing an Undefined Variable
<?php
$attempts++;
var_dump($attempts);
Output
PHP Warning: Undefined variable $attempts in /path/script.php on line 2
int(1)
PHP treats the undefined variable as null and produces 1, but warns about it. Initialize counters ($attempts = 0;) or, for array elements, use ??= before incrementing.
Decrementing Null or Booleans
Effect: The value does not change, and PHP 8.3+ emits a warning.
Fix: Initialize with integers.
Relying on Prefix/Postfix Differences in Complex Expressions
$result = $i++ + ++$i;
Effect: Code that changes and reads the same variable several times in one expression is very hard to understand.
Fix: Split it into separate statements.
Using ++ to Generate Letter Sequences
Effect: Deprecation notices in newer PHP versions and confusing decrement behavior.
Fix: Use str_increment() (PHP 8.3+), or range('A', 'Z') for simple letter lists.
Best Practices
- Use
++and--for integer counters, and initialize counters to0. - Use the operators as standalone statements whenever possible; then prefix and postfix are equivalent.
- When the returned value matters, use the form whose timing you need, and keep the expression simple.
- Use
$counts[$key] ??= 0; $counts[$key]++;(orarray_count_values()) for counting. - Use
str_increment()/str_decrement()for letter sequences in PHP 8.3+.
Official reference: https://www.php.net/manual/en/language.operators.increment.php