Incrementing/Decrementing Operators in PHP
What are the Incrementing/Decrementing Operators ?
Explanation
PHP supports pre/post increment and decrement operators. The following table lists all the operators
Example | Name | Effect |
++$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. |
Post Increment/Decrement Operators
Example :
<?php
$a = 5;
//Post Increment
echo "Value of a: " . $a++ ."<br />n";
echo "Value of a post incremented: " . $a . "<br />n";
//Post Decrement
$a = 5;
echo "Value of a: " . $a-- . "<br />n";
echo "Value of a post decremented: " . $a . "<br />n";
?>
Result :
Value of a: 5
Value of a post incremented: 6
Value of a: 5
Value of a post decremented: 4
In the above example, when the post increment or decrement operator is called it returns the same value, after that it increments or decrements the value.
Pre Increment/Decrement Operators
Example :
<?php
Pre Increment
$a = 5;
echo "Pre incremented value: " .++$a . "<br />n";
echo "Value is same: " .$a . "<br />n";
Pre Decrement
$a = 5;
echo "Pre decremented value: ".--$a ."<br />n";
echo "Value is same: ".$a ."<br />n";
?>
Result :
Pre incremented value: 6
Value is same: 6
Pre decremented value: 4
Value is same: 4
In the above example, when the pre increment or decrement operator is called it returns decremented or incremented value first.