Increment and decrement operators are used to increase or decrease a variable's value by one. They are widely used in loops (like for and while) and for simple counter updates.
The following table lists the four variations of these operators:
| Operator | Name | Description |
|---|---|---|
++$x |
Pre-increment | Increments $x by one, then returns $x |
$x++ |
Post-increment | Returns $x, then increments $x by one |
--$x |
Pre-decrement | Decrements $x by one, then returns $x |
$x-- |
Post-decrement | Returns $x, then decrements $x by one |
The position of the ++ or -- symbols determines when the value is updated relative to when it is used in the rest of the expression.
Think of it as "Update then Use." PHP first adds one to the variable, and the new value is used immediately.
<?php
$x = 10;
echo ++$x; // Outputs: 11
// $x is now 11
?>
Think of it as "Use then Update." PHP first uses the current value of the variable, and only *after* that statement is finished does it add one.
<?php
$x = 10;
echo $x++; // Outputs: 10
// BUT internally, $x is now 11!
echo $x; // Outputs: 11
?>
Interestingly, PHP also allows the increment operator (++) to work on strings. It follows the "carry" logic used in Excel columns (A → B, Z → AA).
<?php
$s = "a";
echo ++$s; // Outputs: b
$z = "z";
echo ++$z; // Outputs: aa
?>
--) do not work on strings in PHP. They only work on numerical values.
$i++ inside the update part of a for loop to keep track of iterations.
5++).