← Back to PHP Course | Chapter 3: Operators | Lesson 6 of 8

PHP Increment & Decrement

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
<?php
$x = 5;
echo $x++;
echo "\n";
echo $x;
?>

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
<?php
$x = 5;
echo ++$x;
echo "\n";
echo $x;
?>

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
<?php
$x = 5;
echo $x--;
echo "\n";
echo $x;
?>

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
<?php
$x = 5;
echo --$x;
echo "\n";
echo $x;
?>

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
<?php
$letter = 'a';
$letter++;
echo $letter . "\n";

$letter = 'z';
$letter++;
echo $letter;
?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.