--
Incrementing/Decrementing Operators
PHP supports C-style pre- and post-increment and decrement operators.
Note
: The increment/decrement operators only affect numbers and strings. Arrays, objects and resources are not affected. DecrementingNULL
values has no effect too, but incrementing them results in1
.
Example | Name | Effect |
---|---|---|
++$a | Pre-increment | Increments $a by one, then returns $a. |
$a++ | Post-increment | Returns $a, then increments $a by one. |
--$a | Pre-decrement | Decrements $a by one, then returns $a. |
$a-- | Post-decrement | Returns $a, then decrements $a by one. |
Here's a simple example script:
<?php
echo "<h3>Postincrement</h3>";
$a = 5;
echo "Should be 5: " . $a++ . "<br />\n";
echo "Should be 6: " . $a . "<br />\n";
echo "<h3>Preincrement</h3>";
$a = 5;
echo "Should be 6: " . ++$a . "<br />\n";
echo "Should be 6: " . $a . "<br />\n";
echo "<h3>Postdecrement</h3>";
$a = 5;
echo "Should be 5: " . $a-- . "<br />\n";
echo "Should be 4: " . $a . "<br />\n";
echo "<h3>Predecrement</h3>";
$a = 5;
echo "Should be 4: " . --$a . "<br />\n";
echo "Should be 4: " . $a . "<br />\n";
?>
PHP follows Perl's convention when dea
ling with a
rithmetic opera
tions on cha
ra
cter va
ria
bles a
nd not C's. For exa
mple, in PHP a
nd Perl $a = 'Z'; $a++;
turns $a
into 'AA'
, while in C a = 'Z'; a++;
turns a
into '['
(ASCII va
lue of 'Z'
is 90, ASCII va
lue of '['
is 91). Note tha
t cha
ra
cter va
ria
bles ca
n be incremented but not decremented a
nd even so only pla
in ASCII a
lpha
bets a
nd digits (a
-z, A-Z a
nd 0-9) a
re supported. Incrementing/decrementing other cha
ra
cter va
ria
bles ha
s no effect, the origina
l string is uncha
nged.
Example #1 Arithmetic Operations on Character Variables
<?php
echo '== Alphabets ==' . PHP_EOL;
$s = 'W';
for ($n=0; $n<6; $n++) {
echo ++$s . PHP_EOL;
}
// Digit characters behave differently
echo '== Digits ==' . PHP_EOL;
$d = 'A8';
for ($n=0; $n<6; $n++) {
echo ++$d . PHP_EOL;
}
$d = 'A08';
for ($n=0; $n<6; $n++) {
echo ++$d . PHP_EOL;
}
?>
The above example will output:
== Characters ==
X
Y
Z
AA
AB
AC
== Digits ==
A9
B0
B1
B2
B3
B4
A09
A10
A11
A12
A13
A14
Incrementing or decrementing booleans has no effect.
← Execution Operators
Logical Operators →
© 1997–2017 The PHP Documentation Group
Licensed under the Creative Commons Attribution License v3.0 or later.
https://secure.php.net/manual/en/language.operators.increment.php