Home >Backend Development >PHP Tutorial >How Do Increment and Decrement Operators Work in PHP?
Increment operator
-- Decrement operator
Operation | Effect |
---|---|
$a | Increments $a by one, then returns $a. |
$a | Returns $a, then increments $a by one. |
--$a | Decrements $a by one, then returns $a. |
$a-- | Returns $a, then decrements $a by one. |
These operators can be placed before or after the variable.
The increment/decrement operation is performed on the variable first, then the result is returned.
The variable is returned first, then the increment/decrement operation is performed.
$apples = 10; for ($i = 0; $i < 10; ++$i) { echo 'I have ' . $apples-- . " apples. I just ate one.\n"; }
Output:
I have 10 apples. I just ate one. I have 9 apples. I just ate one. ... I have 1 apples. I just ate one.
Pre-increment is slightly faster because it increments the variable directly, then returns the result. Post-increment creates a temporary variable and returns the original value of the variable, then increments it.
In this example, $i is used to increment the loop counter because it is more efficient.
PHP supports incrementing letters as well:
$i = "a"; while ($i < "c") { echo $i++; }
Output:
a b
After reaching z, the next character is aa, and so on.
The above is the detailed content of How Do Increment and Decrement Operators Work in PHP?. For more information, please follow other related articles on the PHP Chinese website!