Category Archives: PHP-Increment and Decrement Operator

Increment/Decrement operator in php

This may seem a bit confusing, but there is even a shorter shorthand for the common task of adding 1 or subtracting 1 from a variable. To add one to a variable or “increment” use the “++” operator:

* $x++; Which is equivalent to $x += 1; or $x = $x + 1;

To subtract 1 from a variable, or “decrement” use the “–” operator:

* $x–; Which is equivalent to $x -= 1; or $x = $x – 1;

Study this example:

<?php
$a = 5;
echo “<h2>A initially is “.$a.”.</h2>”;
echo “<h3>Postincrement</h3>”;
echo “Should be 5: ” . $a++ . “<br />\n”;
echo “Should be 6: ” . $a . “<br />\n”;
echo “<h3>Preincrement</h3>”;
$a = 5;
echo “A is reset to: “.$a. “<br />\n”;
echo “Should be 6: ” . ++$a . “<br />\n”;
echo “Should be 6: ” . $a . “<br />\n”;
echo “<h3>Postdecrement</h3>”;
$a = 5;
echo “A is reset to: “.$a. “<br />\n”;
echo “Should be 5: ” . $a– . “<br />\n”;
echo “Should be 4: ” . $a . “<br />\n”;
echo “<h3>Predecrement</h3>”;
$a = 5;
echo “A is reset to: “.$a. “<br />\n”;
echo “Should be 4: ” . –$a . “<br />\n”;
echo “Should be 4: ” . $a . “<br />\n”;
?>