PHP - Incrementing and decrementing operators

Introduction

Incrementing/decrementing operators are shortcuts for += or -=, and they only work on variables.

  • ++: This operator on the left of the variable will increase the variable by 1, and then return the result. On the right, it will return the content of the variable, and after that increase it by 1.
  • --: This operator works the same as ++ but decreases the value by 1 instead of increasing by 1.

Demo

<?php
     $a = 3; //  w  ww.  j av  a2  s .  c o  m
     $b = $a++; // $b is 3, $a is 4 
     var_dump($a, $b); 
     $b = ++$a; // $a and $b are 5 
     var_dump($a, $b); 
?>

Result

Here, on the first assignment to $b, we use $a++.

The operator on the right will return first the value of $a, which is 3, assign it to $b, and only then increase $a by 1.

In the second assignment, the operator on the left first increases $a by 1, changes the value of $a to 5, and then assigns that value to $b.

Related Topics