Increment/decrement Operators

Operator Description Example Result
++ Pre-Increment ++$a Increments $a by one, then returns $a.
++ Post-Increment $a++ Returns $a, then increments $a by one.
-- Pre-Decrement --$a Decrements $a by one, then returns $a.
-- Post-Decrement $a-- Returns $a, then decrements $a by one.

<html>
<head>
<title>PHP</title>
<meta Name="Author" Content="Hann So">
</head>
<body>
<p>
<?php
echo "<h3>Pre-Increment";
$a = 15;
echo "a = ", $a,"<br />";
echo "Pre-Increment ++a: ", ++$a, "<br />";
echo "The value of a is: ", $a, "<br />";

echo "<h3>Post-Increment</h3>";
$a = 15;
echo "a = ", $a,"
"; echo "Post-Increment a++: ", $a++, "<br />"; echo "The value of a is: ", $a, "<br />"; echo "<h3>Pre-Decrement</h3>"; $a = 15; echo "a = ", $a,"
"; echo "Pre-Decrement --a: ", --$a, "<br />"; echo "The value of a is: ", $a, "<br />"; echo "<h3>Post-Decrement</h3>"; $a = 15; echo "a = ", $a,"
"; echo "Post-Decrement a--: ", $a--, "<br />"; echo "The value of a is: ", $a, "<br />"; ?> </p> </body> </html>

View the effect

Here is an example.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="EN" lang="EN">
<head>
<title>Arithmetic Operators</title>
<meta Name="Author" Content="Hann So">
</head>
<body>
<h2>Auto Parts</h2>
<b>Your order is as follows:</b>
<p>

<?php
$tireqty = 2;
$oilqty = 3;
$sparkqty = 3;
define('TIREPRICE', 50);
define('OILPRICE', 10);
define('SPARKPRICE', 4);
define('SALESTAX', 8.25);

$totalqty = $tireqty + $oilqty + $sparkqty;

$total = $tireqty * TIREPRICE + $oilqty * OILPRICE + $sparkqty * SPARKPRICE;

echo "$tireqty tires<br />";
echo "$oilqty bottles of oil<br />";
echo "$sparkqty spark plugs<br />";
echo "Items ordered: $totalqty<br />";
echo "Subtotal: \$$total<br />";

$saletax = SALESTAX/100; // Divide the sales tax by 100
$tax = $total * $saletax; // Calculate the sales tax
$saletax++; // Add 1 to the sales tax
$total = $total * $saletax; // Calculate the total
echo "Tax: \$$tax<br />";
echo "Total: \$$total";
?>

</p>
</body>
</html>

View the effect


Operators | Arithmetic | Increment/Decrement | Assignment | Comparison | Logical | Execution | String | Bitwise | Ternary | Operator Precedence
© 2008: Hann So
email: hso@voyager.deanza.edu