Arithmetic Operators

Arithmetic operators are used to perform mathematical operations on variables and literals.

Operator Description Example Result
- Negation -$a Opposite of $a.
+ Addition $a + $b Sum of $a and $b.
- Subtraction $a - $b Difference of $a and $b.
* Multiplication $a * $b Product of $a and $b.
/ Division $a / $b Quotient of $a and $b.
The division operator ("/") returns a float value unless the two operands are integers (or strings that get converted to integers) and the numbers are evenly divisible, in which case an integer value will be returned.
% Modulus (division remainder) $a % $b Remainder of $a divided by $b.
Operands of modulus are converted to integers (by stripping the decimal part) before processing.

<html>
<head>
<title>PHP</title>
<meta Name="Author" Content="Hann So">
</head>
<body>
<p>
<?php
$a = 15;
$b = 4;
echo "a = ", $a,"<br />b = ",$b, "<br />";
echo "Negation of a = -$a is: ", -$a, "<br />";
echo "Addition of a+b = $a+$b is: ", $a+$b, "<br />";
echo "Subtraction of a-b = $a-$b is: ", $a-$b, "<br />";
echo "Multiplication of $a*$b = $a*$b is: ", $a*$b, "<br />";
echo "Division of a/b = $a/$b is: ", $a/$b, "<br />";
echo "Modulus of a%b = $a%$b is: ", $a%$b, "<br />";
?>
</p>
</body>
</html>

View the effect

Here is an example on using the arithmetic operators.

<!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>
<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;
$tax = $total * SALESTAX/100;
$totalamount = $total + $tax;
?>

</p>
<h2>Auto Parts</h2>
<b>Your order is as follows:</b>
<p>

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

</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