Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท Operators

PHP increment and decrement operators

Reference for PHP ++ and --: pre- and post-increment, numeric strings, null behavior, overflow, and why string increment is deprecated in favor of str_increment().

++ adds one to a variable and -- subtracts one. Each comes in two forms. The prefix form (++$i) changes the variable first and returns the new value. The postfix form ($i++) returns the old value and then changes the variable.

PHP has historically also incremented non-numeric strings in a Perl-like way: "a" became "b" and "z" became "aa". Current PHP deprecates that behavior with ++. If you need it (spreadsheet column names, short codes), call str_increment() explicitly.

PHP
$i = 5;
echo $i++;  // 5, then $i is 6
echo ++$i;  // 7

Try it

PHP Pre and post forms

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP Alphanumeric increment, the explicit way

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
++$a    $a++    --$a    $a--
Form Returns Effect
++$a New value Increments $a
$a++ Old value Increments $a
--$a New value Decrements $a
$a-- Old value Decrements $a

Usage notes

  • Postfix keeps a copy. Use the prefix form when you ignore the result; it states intent and is never slower.
  • Integer overflow turns into float. Incrementing PHP_INT_MAX gives a float.
  • Numeric strings are numbers: "5"++ gives the integer 6 and "1.5"++ gives the float 2.5.
  • Non-numeric strings are deprecated. "a"++ still gives "b", but PHP 8.5 emits a deprecation notice telling you to use str_increment(). That function (added in PHP 8.3) works on ASCII letters and digits only, carries over ("Az" to "Ba", "zz" to "aaa", "a9" to "b0") and throws ValueError for an empty or non-alphanumeric string. str_decrement() is the reverse.
  • null is uneven. null++ gives 1, but null-- stays null, and in PHP 8.5 decrementing null emits a warning that this will change in the next major version. Do not rely on either.
  • Arrays and objects cannot be incremented: that throws TypeError.
  • Don't use the same variable twice in one expression ($i + $i++): the order of evaluation is easy to misjudge.
  • Properties and array elements can be incremented too ($counts[$word]++). A missing key raises a warning, so write $counts[$word] = ($counts[$word] ?? 0) + 1 for counters.