Increment / Decrement Operators

Ma Mahalakshmi V Updated 14 Nov 2026
7 min read ·Lesson 40 of 255

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 Intro PHP Install PHP Built-in Web Server PHP Syntax PHP Tags PHP and HTML PHP Comments PHP Multiline Comments PHP Variables Variables Scope Static Variables Variable Variables PHP Echo / Print PHP printf / sprintf PHP Data Types PHP Booleans PHP NULL PHP Strings String Functions Modify Strings Concatenate Strings Slicing Strings Escape Characters String Interpolation Heredoc and Nowdoc Search in Strings Multibyte Strings PHP Floats PHP Casting PHP Type Juggling PHP Math PHP Random Numbers PHP Constants PHP Magic Constants PHP Operators Arithmetic Operators Assignment Operators Comparison Operators Increment / Decrement Operators Logical Operators Null Coalescing Operator Spaceship Operator Operator Precedence PHP If...Else...Elseif PHP If PHP If Operators PHP If...Else PHP Shorthand if PHP Nested if PHP Switch PHP Match Alternative Syntax PHP Loops While Loop Do While Loop For Loop Foreach Loop Nested Loops Break Statement Continue Statement PHP Functions User-defined Functions Function Arguments Default Argument Values Pass by Reference Named Arguments Variadic Functions Return Values Type Declarations in Functions Recursive Functions Variable Functions Anonymous Functions Closures Arrow Functions First-class Callable Syntax PHP Arrays Indexed Arrays Associative Arrays Create Arrays Access Array Items Update Array Items Add Array Items Remove Array Items Sorting Arrays Multidimensional Arrays Array Destructuring Array Spread Operator Search in Arrays Merge Arrays array_map / array_filter / array_reduce Array Functions PHP Superglobals $GLOBALS $_SERVER $_REQUEST $_POST $_GET $_FILES $_COOKIE $_SESSION \$\_ENV PHP RegEx RegEx Patterns RegEx Modifiers preg_match preg_replace preg_split PHP RegEx Functions PHP Form Handling PHP Form Validation PHP Form Required PHP Form URL/E-mail Form Input Sanitizing Escaping Output (htmlspecialchars) Checkbox, Radio and Select Inputs Sticky Forms PHP Form Complete PHP Date and Time Date Formatting DateTime Class Timezones PHP Include Include vs Require PHP File Handling PHP File Open/Read PHP File Create/Write File Delete / Rename / Copy PHP Directories PHP CSV Files PHP File Upload PHP Cookies PHP Sessions PHP Filters PHP Filters Advanced PHP Callback Functions PHP JSON PHP Exceptions Error Handling Custom Error Handler Error Logging HTTP Headers and Redirects Output Buffering Sending Email PHP cURL Consuming REST APIs PHP Generators PHP What is OOP PHP Classes/Objects The $this Keyword PHP Properties PHP Methods PHP Constructor Constructor Property Promotion PHP Destructor PHP Access Modifiers Readonly Properties PHP Inheritance Method Overriding The final Keyword PHP Class Constants PHP Abstract Classes PHP Interfaces Polymorphism PHP Traits PHP Static Methods PHP Static Properties Late Static Binding Magic Methods Object Cloning Comparing Objects Anonymous Classes PHP Enums PHP Namespaces Autoloading Classes PHP Iterables Iterators Object Serialization Strict Types Union Types Nullable Types Mixed and Never Types Nullsafe Operator PHP Attributes PHP Fibers Readonly Classes Property Hooks (PHP 8.4) Asymmetric Visibility (PHP 8.4) Reflection API SPL Data Structures MySQL Database MySQL Connect MySQL Create DB MySQL Create Table MySQL Insert Data MySQL Get Last ID MySQL Insert Multiple MySQL Prepared MySQL Select Data MySQL Where MySQL Order By MySQL Delete Data MySQL Update Data MySQL Limit Data MySQL Joins with PHP Pagination with PHP PDO Introduction PDO Connect PDO Prepared Statements PDO Fetch Modes PDO Transactions PDO Error Handling PHP XML Parsers PHP SimpleXML Parser PHP SimpleXML - Get PHP XML Expat Parser PHP DOM Parser PHP XMLReader PHP XMLWriter AJAX Intro AJAX PHP AJAX Database AJAX XML AJAX Live Search AJAX Poll AJAX with JSON Security Introduction Password Hashing SQL Injection Prevention XSS Prevention CSRF Protection Session Security Secure Cookies File Upload Security Filesystem Security Error Reporting in Production Hiding PHP Encryption with Sodium PHP Configuration (php.ini) PHP Command Line (CLI) Composer PSR-4 Autoloading Installing Extensions (PECL / PIE) Debugging PHP OPcache & Performance Garbage Collection PHP-FPM Migrating to PHP 8 Project: Contact Form with Email Project: Login & Registration System Project: CRUD App with MySQL Project: Image Upload Gallery Project: Shopping Cart with Sessions Project: Simple Blog Project: REST API with PHP
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.