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

Piotr Zatorski
2 min readNov 21, 2020

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

PHP supports incrementation and decrementation

The increment and decrement operators work only on strings and numbers. On objects, tables, booleans and resources they do nothing. 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)

--

--

Piotr Zatorski
Piotr Zatorski

Written by Piotr Zatorski

PHP Developer with more than 5 years expierence

No responses yet