Category Archives: Differnce between Post Increment and Pre Increment

PHP post and pre increment

Increment/decrement 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.

Try this example:

<?php
echo “<h3>Postincrement</h3>”;
$a = 5;
echo “Should be 5: ” . $a++ . “<br />\n”;
echo “Should be 6: ” . $a . “<br />\n”;

echo “<h3>Preincrement</h3>”;
$a = 5;
echo “Should be 6: ” . ++$a . “<br />\n”;
echo “Should be 6: ” . $a . “<br />\n”;

echo “<h3>Postdecrement</h3>”;
$a = 5;
echo “Should be 5: ” . $a– . “<br />\n”;
echo “Should be 4: ” . $a . “<br />\n”;

echo “<h3>Predecrement</h3>”;
$a = 5;
echo “Should be 4: ” . –$a . “<br />\n”;
echo “Should be 4: ” . $a . “<br />\n”;
?>
Output:


Postincrement
Should be 5: 5
Should be 6: 6
Preincrement
Should be 6: 6
Should be 6: 6
Postdecrement
Should be 5: 5
Should be 4: 4
Predecrement
Should be 4: 4
Should be 4: 4