PHP
➕ Increment and Decrement Operators in PHP
Increment and Decrement Operators in PHP are shorthand unary operators used to increase or decrease a variable's numeric value by exactly 1. They are heavily utilized inside loop counters (such as for and while) and tracking variables.
-
Key Difference (Pre vs. Post): Placing the operator before the variable (
++$x) modifies the variable first and returns the updated value. Placing it after ($x++) returns the original value first and then increments or decrements the variable.
🛠️ Pre-increment and Post-increment
1️⃣ Pre-increment (++$x)
Increments $x by 1 first, then evaluates and returns $x.
$x = 5;
echo ++$x; // Outputs: 6 (Increments $x to 6, then prints)
echo $x; // Outputs: 6
2️⃣ Post-increment ($x++)
Evaluates and returns $x first, then increments $x by 1 afterwards.
$x = 5;
echo $x++; // Outputs: 5 (Prints current value 5, then increments to 6)
echo $x; // Outputs: 6
🛠️ Pre-decrement and Post-decrement
1️⃣ Pre-decrement (--$x)
Decrements $x by 1 first, then evaluates and returns $x.
$x = 5;
echo --$x; // Outputs: 4 (Decrements $x to 4, then prints)
echo $x; // Outputs: 4
2️⃣ Post-decrement ($x--)
Evaluates and returns $x first, then decrements $x by 1 afterwards.
$x = 5;
echo $x--; // Outputs: 5 (Prints current value 5, then decrements to 4)
echo $x; // Outputs: 4
📊 Quick Reference Table
| Operator | Name | Syntax | Description |
|---|---|---|---|
++$x |
Pre-increment | ++$x |
Increments $x by 1, then returns $x. |
$x++ |
Post-increment | $x++ |
Returns $x, then increments $x by 1. |
--$x |
Pre-decrement | --$x |
Decrements $x by 1, then returns $x. |
$x-- |
Post-decrement | $x-- |
Returns $x, then decrements $x by 1. |
-
📝 Short Summary
- Increment/Decrement operators only affect numbers and numeric strings.
-
NULLvalues increment to1, but decrementingNULLhas no effect in PHP. -
Use pre-increment (
++$i) or post-increment ($i++) consistently based on whether the value needs to be modified prior to evaluation.
