PHP - Incrementing / Decrementing Operators

Introduction

It's useful to add or subtract the value 1 (one) over and over.

Two special operators are used to perform this task: the increment and decrement operators.

They are written as two plus signs or two minus signs, respectively, preceding or following a variable name, like so:


++$x; // Adds one to $x and then returns the result
$x++; // Returns $x and then adds one to it
--$x; // Subtracts one from $x and then returns the result
$x--; // Returns $x and then subtracts one from it

Placing the operator before the variable name causes the variable's value to be incremented or decremented before the value is returned.

Placing the operator after the variable name returns the current value of the variable first, then adds or subtracts one from the variable.

For example:

Demo

<?php

    $x = 5;/*  www.j  a v  a  2 s  . co  m*/
    echo ++$x;  // Displays "6" (and $x now contains 6)
    $x = 5;
    echo $x++;  // Displays "5" (and $x now contains 6)
?>

Result

You can use the increment operator with characters as well.

For example, you can add 1 to the character B and the returned value is C.

You cannot subtract from character values.

Related Topic