PHP supports C-style pre/post increment and decrement operators.
Note: Increment/decrement operators do not affect Boolean values. Decrementing a NULL value has no effect, but increasing NULL results in 1.
Increment/Decrease Operator
Example
Name
Effect
++$a Prepend the value of $a by one, and then return $a.
$a++ followed by , returns $a, and then adds one to the value of $a.
--$a Subtracts the value of $a by one, and then returns $a.
$a-- After subtraction returns $a, and then decrements the value of $a by one.
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"; ?>
When dealing with arithmetic operations on character variables, PHP follows Perl's habits instead of C's. For example, in Perl $a = 'Z'; $a++; will turn $a into 'AA', while in C, a = 'Z'; a++; will turn a into '['('Z' The ASCII value of '[' is 90, and the ASCII value of '[' is 91). Note that character variables can only be incremented, not decremented, and only pure letters (a-z and A-Z) are supported. Incrementing/decrementing other character variables is invalid and the original string will not change.
Example #1 Arithmetic operations involving character variables
<?php $i = 'W'; for ($n=0; $n<6; $n++) { echo ++$i . "\n"; } ?>
The above routine will output:
X Y Z AA AB AC