PHP Increment and Decrement Operators Explained with Examples
What Are PHP Increment and Decrement Operators?
In PHP, increment and decrement operators are used to increase or decrease a variable’s value by one.
These are commonly used in:
Loops (
for,while,do-while)Counters
Calculations
Iterations in arrays or database results
Let’s explore both in detail with simple examples.
Increment Operator (++)
The increment operator increases a variable’s value by 1.
PHP provides two types of increment operators:
| Type | Description |
|---|---|
| Pre-increment (++$x) | Increments the value before using it. |
| Post-increment ($x++) | Increments the value after using it. |
Pre-Increment (++$x)
First increases the value, then returns it.
Example:
<?php
$x = 5;
echo ++$x; // Value increases first
?>
Output:
6 Explanation:
The variable $x becomes 6 before it’s printed.
Post-Increment ($x++)
First returns the current value, then increases it.
Example:
<?php
$x = 5;
echo $x++; // Prints first, then increases
echo "<br>";
echo $x; // Now $x is 6
?>
Output:
5 6 Explanation:
The first echo prints the old value, and only then $x is incremented.
Decrement Operator (--)
The decrement operator decreases a variable’s value by 1.
Like increment, it also has two types:
| Type | Description |
|---|---|
| Pre-decrement (–$x) | Decreases the value before using it. |
| Post-decrement ($x–) | Decreases the value after using it. |
Pre-Decrement (--$x)
Decreases first, then returns the new value.
Example:
<?php
$x = 5;
echo --$x;
?>
Output:
4Post-Decrement ($x--)
Returns the current value first, then decreases it.
Example:
<?php
$x = 5;
echo $x--; // Prints first, decreases later
echo "<br>";
echo $x; // Now $x is 4
?>
Output:
5 4Real-Life Example: Student Counter
<?php
$students = 0;
echo "New student joined. Total: " . ++$students . "<br>";
echo "Another joined. Total: " . ++$students . "<br>";
echo "One left. Total: " . --$students . "<br>";
?>
Output:
New student joined. Total: 1 Another joined. Total: 2 One left. Total: 1 Explanation:
Each time a student joins,
++$studentsincreases the count.When one leaves,
--$studentsdecreases it.
Use in Loops
Increment and decrement operators are often used in loops to control iterations.
Example:
<?php
for ($i = 1; $i <= 5; $i++) {
echo "Number: $i <br>";
}
?>
Output:
Number: 1 Number: 2 Number: 3 Number: 4 Number: 5Here $i++ increases by 1 in every iteration.