Pre and post increment / decrement — how do they work?

PHP supports the increment and decrement system known from the C language. See how they work.

Image for post
PHP supports incrementation and decrementation

The increment and decrement operators work only on strings and numbers. On objects, tables, booleans and resources do not matter. Regarding null, decrementation does not matter, but incrementation returns 1.

++$a — Pre-increment — Increments $a by one, then returns $a.

$a++ — Post-increment — Returns $a, then increments $a by one.

--$a — Pre-decrement — Decrements $a by one, then returns $a.

$a-- — Post-decrement — Returns $a then decrements $a by one.

Number pre-increment example

$i = 1;
echo (++$i + 1); // 3
echo $i; // 2

Number post-increment example

$i = 1;
echo ($i++ + 1); // 2
echo $i; // 2

Number pre-decrement example

$i = 1;
echo ( —- $i + 1); // 1
echo $i; // 0

Number post-decrement example

$i = 1;
echo ($i —- + 1); // 2
echo $i; // 0

How about strings (chars)

The easiest way is to illustrate the operation on an example (i.e. nothing new). Amazingly, PHP handles this surprisingly well and intuitively.

$c = 'W';
++$c; // 'Y'
++$c; // 'Z'
++$c; // 'AA'
++$c; // 'AB'
// Next example
$c = 'A8';
++$c; // 'A9'
++$c; // 'B0'
// ...
++$c; // 'Z9'
++$c; // 'AA0'
// Next example
$c = 'A08';
++$c; // 'A09'
// ...
++$c; // 'A99'
++$c; // 'B00'
// ...
++$c; // 'Z99'
++$c; // 'AA00'

Low level information regarding post increment / decrement.

Analyzing the examples above, we can see an interesting thing about post-increment. According to logic in mathematical terms, we always execute the code in the middle of the parenthesis then go to the echo function.

Think about this.

Since it is not possible to return to the parenthesis, all operations in it should be performed first. So how does it happen that we do not get a result similar to the case with post increment / decrement?

PHP in memory copies the value of a variable into this its out-of-the-box variable, which causes that we have two values in memory.

The obvious conclusion is that micro performance is falling. Wherever you can, you should use pre-incrementation / decrementation.

Written by

PHP Developer with more than 5 years expierence

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store