PHP Increment & Decrement
In this page:
Post-Increment Operator
$x++ (post-increment) reads out $x's current value first, and only *after* that read does PHP add 1 to the variable. If you use the expression's result directly, you get the value from before the increment — the update happens, just invisibly to that particular expression.
Example: Post-Increment Operator
<?php
$x = 5;
echo $x++;
echo "\n";
echo $x;
?>
Login to try C/C++/Java/PHP code in the editor
Pre-Increment Operator
++$x (pre-increment) adds 1 to the variable first, then returns the already-updated value. Whether you use pre- or post-increment only matters when you use the expression's *result* somewhere else in the same line — as a standalone statement, $x++ and ++$x behave identically.
Example: Pre-Increment Operator
<?php
$x = 5;
echo ++$x;
echo "\n";
echo $x;
?>
Login to try C/C++/Java/PHP code in the editor
Post-Decrement Operator
$x-- (post-decrement) mirrors post-increment: it returns the current value, then subtracts 1 afterward. It's the natural choice for a countdown loop where you want to act on the value *before* it decreases on that iteration.
Example: Post-Decrement Operator
<?php
$x = 5;
echo $x--;
echo "\n";
echo $x;
?>
Login to try C/C++/Java/PHP code in the editor
Pre-Decrement Operator
--$x (pre-decrement) subtracts 1 first and returns the new, already-lower value. As with pre-increment, the difference from the post- version only shows up when the expression's return value is actually consumed rather than the statement standing alone.
Example: Pre-Decrement Operator
<?php
$x = 5;
echo --$x;
echo "\n";
echo $x;
?>
Login to try C/C++/Java/PHP code in the editor
Incrementing Characters
PHP has an unusual extra ability: incrementing a string containing letters advances it alphabetically — $letter = a; $letter++; produces b, and incrementing z rolls over to aa, the same way a car odometer carries over a digit.
Example: Incrementing Characters
<?php
$letter = 'a';
$letter++;
echo $letter . "\n";
$letter = 'z';
$letter++;
echo $letter;
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: