Home >Backend Development >PHP Tutorial >How Do Increment and Decrement Operators Work in PHP?

How Do Increment and Decrement Operators Work in PHP?

Linda Hamilton
Linda HamiltonOriginal
2025-01-01 06:37:11215browse

How Do Increment and Decrement Operators Work in PHP?

Symbols in PHP

Incrementing/Decrementing Operators

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.

Usage

These operators can be placed before or after the variable.

Before the variable

The increment/decrement operation is performed on the variable first, then the result is returned.

After the variable

The variable is returned first, then the increment/decrement operation is performed.

Example

$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 vs. Post-increment

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.

Incrementing Letters

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn