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.
$i = 5; echo $i++; // 5, then $i is 6 echo ++$i; // 7
Try it
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.
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
++$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_MAXgives a float. - Numeric strings are numbers:
"5"++gives the integer6and"1.5"++gives the float2.5. - Non-numeric strings are deprecated.
"a"++still gives"b", but PHP 8.5 emits a deprecation notice telling you to usestr_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 throwsValueErrorfor an empty or non-alphanumeric string.str_decrement()is the reverse. nullis uneven.null++gives1, butnull--staysnull, and in PHP 8.5 decrementingnullemits 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) + 1for counters.