php increment and decrement operators

The increment (++) and decrement (--) operators present a minor convenience in terms of code clarity, providing shortened means by which you can add 1 to or subtract 1 from the current value of a variable.

Example Label Outcome
++$a, $a++ Increment Increment $a by 1
--$a, $a-- Decrement Decrement $a by 1

These operators can be placed on either side of a variable, and the side on which they are placed provides a slightly different effect. Consider the outcomes of the following examples:


<?php
$inv = 15; // Assign integer value 15 to $inv.
$oldInv = $inv--; // Assign $oldInv the value of $inv, then decrement $inv.
$origInv = ++$inv; // Increment $inv, then assign the new $inv value to $origInv
?>

As you can see, the order in which the increment and decrement operators are used has an important effect on the value of a variable.

Prefixing the operand with one of these operators is known as a preincrement and predecrement operation, while postfixing the operand is known as a postincrement and postdecrement operation.





Content