Increment / Decrement Operators

sa sahaya jerish Updated 17 Oct 2026
7 min read ·Lesson 89 of 109
In this post

What Are Increment and Decrement Operators? In simple terms: The increment operator ++ adds 1 to a variable, and the decrement operator -- subtracts 1. They are shortcuts for counting up and down. Tec

What Are Increment and Decrement Operators?

In simple terms: The increment operator ++ adds 1 to a variable, and the decrement operator -- subtracts 1. They are shortcuts for counting up and down.

Technically: ++ and -- are unary operators that modify a variable in place and return a value. Each has two forms — prefix (++$i) and postfix ($i++) — which differ in the value they return.

OperatorNameEffectReturns
++$aPre-incrementAdds 1 to $aThe new value
$a++Post-incrementAdds 1 to $aThe old value
--$aPre-decrementSubtracts 1 from $aThe new value
$a--Post-decrementSubtracts 1 from $aThe old value

Why They Exist

Counting by one is extremely common: loop counters, page views, retry attempts, item counts, positions in a list. $i++ is shorter than $i = $i + 1 or $i += 1, and it is instantly recognizable to developers from almost every C-style language.


Basic Usage

Example

<?php
$visitors = 0;

$visitors++;
$visitors++;
$visitors++;

echo "Visitors: $visitors\n";

$seatsLeft = 5;
$seatsLeft--;

echo "Seats left: $seatsLeft\n";

Output

Visitors: 3
Seats left: 4

When the operator is used as a standalone statement, the prefix and postfix forms behave identically: the variable changes by 1, and the returned value is ignored.


Prefix vs Postfix

The difference matters only when the result of the expression is used.

Example

<?php
$i = 5;
$a = $i++;   // post-increment: $a gets the OLD value
echo "a = $a, i = $i\n";

$j = 5;
$b = ++$j;   // pre-increment: $b gets the NEW value
echo "b = $b, j = $j\n";

$k = 5;
echo $k-- . "\n";   // prints 5, then $k becomes 4
echo --$k . "\n";   // $k becomes 3, prints 3

Output

a = 5, i = 6
b = 6, j = 6
5
3

Step by Step

StatementWhat HappensResult
$a = $i++Copy the current value (5) to $a, then increase $i$a = 5, $i = 6
$b = ++$jIncrease $j to 6, then copy it to $b$b = 6, $j = 6
echo $k--Print the current value (5), then decrease $kprints 5, $k = 4
echo --$kDecrease $k to 3, then print itprints 3

A simple way to remember: the position of the operator tells you when the change happens relative to reading the value. Prefix: change first, then read. Postfix: read first, then change.


Using Increment in Loops

The most common use is the loop counter:

<?php
for ($i = 1; $i <= 5; $i++) {
    echo "Lesson $i\n";
}

$countdown = 3;
while ($countdown > 0) {
    echo "Starting in $countdown...\n";
    $countdown--;
}
echo "Go!\n";

Output

Lesson 1
Lesson 2
Lesson 3
Lesson 4
Lesson 5
Starting in 3...
Starting in 2...
Starting in 1...
Go!

In the for loop's third part, the result of $i++ is not used, so $i++ and ++$i are equivalent. Loops are covered in For Loop and While Loop.


Using the Returned Value

Postfix increment is useful when you need the current position and then want to advance it:

<?php
$items = [];
$nextId = 101;

$items[$nextId++] = 'Keyboard';
$items[$nextId++] = 'Mouse';
$items[$nextId++] = 'Monitor';

print_r($items);
echo "Next ID will be: $nextId\n";

Output

Array
(
    [101] => Keyboard
    [102] => Mouse
    [103] => Monitor
)
Next ID will be: 104

Each assignment uses the current ID as the key and then advances it. This is compact, but keep such expressions simple — combining several increments with other operations in one expression quickly becomes hard to read.

Counting Occurrences

<?php
$text = "the cat and the hat and the bat";
$counts = [];

foreach (explode(' ', $text) as $word) {
    $counts[$word] ??= 0;
    $counts[$word]++;
}

arsort($counts);
print_r($counts);

Output

Array
(
    [the] => 3
    [and] => 2
    [cat] => 1
    [hat] => 1
    [bat] => 1
)

How It Works

  1. explode(' ', $text) splits the sentence into words.
  2. $counts[$word] ??= 0 creates the key with 0 the first time a word appears, avoiding an "Undefined array key" warning.
  3. $counts[$word]++ increases that word's count.
  4. arsort() sorts by count in descending order while keeping the keys. (Words with equal counts keep their original order.)

PHP also offers array_count_values(), which does the same counting in one call: array_count_values(explode(' ', $text)).


Increment and Decrement With Different Types

++ and -- are designed for integers and floats. With other types, the behavior is inconsistent, which is why recent PHP versions warn about several cases.

Value++ Result-- Result
5 (int)64
5.5 (float)6.54.5
"5" (numeric string)int(6)int(4)
"5.5" (numeric string)float(6.5)float(4.5)
nullint(1)stays null (warning since PHP 8.3)
true / falseunchanged (warning since PHP 8.3)unchanged (warning since PHP 8.3)
"a" (alphanumeric string)"b" (see below)unchanged
PHP_INT_MAXbecomes a float—

Example

<?php
$fromForm = "7";
$fromForm++;
var_dump($fromForm);

$total = null;
$total++;
var_dump($total);

$price = 9.5;
$price--;
var_dump($price);

Output

int(8)
int(1)
float(8.5)
  • A numeric string is converted to a number and then incremented.
  • Incrementing null produces 1 — but decrementing null leaves it as null. This asymmetry is a common surprise; since PHP 8.3, decrementing null emits the warning "Decrement on type null has no effect, this will change in the next major version of PHP".
  • Incrementing or decrementing a boolean has no effect; since PHP 8.3 it emits a warning as well.

Rule: initialize counters with 0 (an integer) before using ++ or --.


Incrementing Letters: Alphanumeric Strings

For historical reasons, ++ on a non-numeric string follows Perl's "alphanumeric increment" rules:

<?php
$letter = 'a';
$letter++;
var_dump($letter);

$column = 'Z';
$column++;
var_dump($column);

$code = 'A9';
$code++;
var_dump($code);

Output (PHP 8.3 / 8.4)

string(1) "b"
string(2) "AA"
string(2) "B0"

The last character is advanced, and it "carries over" like a counter: Z becomes AA (similar to spreadsheet column names) and A9 becomes B0. -- does not reverse this; decrementing 'b' leaves it unchanged.

Because this behavior is surprising and inconsistent, PHP is phasing it out. PHP 8.3 added dedicated functions, and newer PHP versions deprecate using ++ on non-numeric strings:

<?php
var_dump(str_increment('Az'));
var_dump(str_increment('zz'));
var_dump(str_decrement('Ba'));
var_dump(str_decrement('aa'));

Output

string(2) "Ba"
string(3) "aaa"
string(2) "Az"
string(1) "z"

str_increment() and str_decrement() (PHP 8.3+) make the intent explicit, work symmetrically, and throw a ValueError for invalid input (for example, str_decrement('a') has no previous value).


Common Mistakes

Assigning a Post-Increment to the Same Variable

<?php
$i = 5;
$i = $i++;

var_dump($i);

Output

int(5)

$i++ returns the old value (5), increments $i to 6, and then the assignment overwrites $i with the returned 5. The increment is lost. Use either $i++; or $i = $i + 1; — never both.

Incrementing an Undefined Variable

<?php
$attempts++;
var_dump($attempts);

Output

PHP Warning:  Undefined variable $attempts in /path/script.php on line 2
int(1)

PHP treats the undefined variable as null and produces 1, but warns about it. Initialize counters ($attempts = 0;) or, for array elements, use ??= before incrementing.

Decrementing Null or Booleans

Effect: The value does not change, and PHP 8.3+ emits a warning.

Fix: Initialize with integers.

Relying on Prefix/Postfix Differences in Complex Expressions

$result = $i++ + ++$i;

Effect: Code that changes and reads the same variable several times in one expression is very hard to understand.

Fix: Split it into separate statements.

Using ++ to Generate Letter Sequences

Effect: Deprecation notices in newer PHP versions and confusing decrement behavior.

Fix: Use str_increment() (PHP 8.3+), or range('A', 'Z') for simple letter lists.


Best Practices

  • Use ++ and -- for integer counters, and initialize counters to 0.
  • Use the operators as standalone statements whenever possible; then prefix and postfix are equivalent.
  • When the returned value matters, use the form whose timing you need, and keep the expression simple.
  • Use $counts[$key] ??= 0; $counts[$key]++; (or array_count_values()) for counting.
  • Use str_increment() / str_decrement() for letter sequences in PHP 8.3+.

Official reference: https://www.php.net/manual/en/language.operators.increment.php

0 Comments

Reviewed before they appear

No comments yet.

PHP
PHP Home PHP Switch PHP Match Alternative Syntax PHP Loops While Loop Do While Loop For Loop Foreach Loop Nested Loops Break Statement PHP Home PHP Intro PHP Install PHP Built-in Web Server PHP Syntax PHP Tags PHP and HTML PHP Comments PHP Multiline Comments PHP Variables Variables Scope PHP Casting Logical Operators Null Coalescing Operator Spaceship Operator Operator Precedence Continue Statement Modify Strings PHP If...Else...Elseif PHP If Modify Strings PHP If Operators PHP Functions Concatenate Strings PHP If...Else Slicing Strings User-defined Functions Slicing Strings PHP Shorthand if Escape Characters Default Argument Values PHP Nested if Pass by Reference String Interpolation Named Arguments PHP File Upload Variadic Functions Return Values Search in Strings Multibyte Strings Type Declarations in Functions PHP Numbers PHP Math PHP Floats PHP Random Numbers PHP Constants PHP Properties PHP Methods PHP Constructor Constructor Property Promotion PHP Cookies PHP Destructor PHP Access Modifiers Readonly Properties PHP Sessions PHP Inheritance Method Overriding PHP Filters The final Keyword CSRF Protection PHP Filters Advanced Session Security Secure Cookies PHP Magic Constants File Upload Security PHP Callback Functions PHP Operators Filesystem Security PHP JSON Arithmetic Operators Error Reporting in Production Hiding PHP Assignment Operators PHP Configuration (php.ini) Comparison Operators PHP Command Line (CLI) PHP Exceptions Increment / Decrement Operators Migrating to PHP 8 PHP Form Validation PHP Form Required PHP Form URL/E-mail Error Handling Form Input Sanitizing Escaping Output (htmlspecialchars) Custom Error Handler Checkbox, Radio and Select Inputs Sticky Forms PHP Form Complete PHP Date and Time Date Formatting Error Logging HTTP Headers and Redirects Output Buffering Sending Email PHP cURL Consuming REST APIs PHP Generators
Ask about this post
AI Ask about this post

Ask questions about Increment / Decrement Operators and get answers drawn from it.

Signed-in readers only.