Adding or subtracting 1 is so common that PHP has a shortcut.
| Operator | Meaning |
|---|---|
$i++ | Add 1 to $i |
$i-- | Subtract 1 from $i |
<?php
$count = 5;
$count++;
echo $count . "\n";
$count--;
$count--;
echo $count;
6
4
Prefix and postfix
The operator can come before or after the variable, and that changes what the expression returns.
- Postfix (
$i++): returns the old value, then adds 1. - Prefix (
++$i): adds 1 first, then returns the new value.
<?php
$a = 5;
echo $a++ . "\n"; // prints 5, then $a becomes 6
echo $a . "\n";
$b = 5;
echo ++$b . "\n"; // $b becomes 6, then prints 6
echo $b;
5
6
6
6
When you use ++ as its own statement, as in $i++;, both forms do exactly the same thing.
Where you see it
Counting inside a loop:
<?php
for ($i = 1; $i <= 3; $i++) {
echo "Round $i\n";
}
Round 1
Round 2
Round 3
Counting how many times something happens:
<?php
$words = ["php", "sql", "php", "css", "php"];
$phpCount = 0;
foreach ($words as $word) {
if ($word === "php") {
$phpCount++;
}
}
echo $phpCount;
3
Keep it on its own line
$total = $i++ + ++$i; is legal and hard to read. Use ++ and -- as separate statements so nobody has to think about the order.