Arithmetic Operators

PHP has the following operators:
OperatorPurposeExample
+addition $x=3+5;
- minus $x=$j-2;
* multiply $total=$amount*$quantity;
/ divide $pkgs=$quantity/12; //1 pkg=1dozen
% remainder $remainder=$quantity%12


The % (mod) operator is used to find the remainder. Before children learn about decimal numbers, they may give the answer to division problems as:
"17 divided by 5 is 3 with a remainder of 2"
Note that 17/5 results in 3, while 17 % 5 results in 2. The mod operator is useful in manufacturing and other types of problems such as the example where we divide the quantity by 12 to find out how many packages we can make, but also want to know how many will be left over.

Example: We have the number of inches and want to print feet and inches:

<?php
echo $inches.'" = '.(int)($inches/12)."'".($inches%12).'"<BR>';
echo $inches.'" = '.$inches*2.54.'CM<BR>';
?> 

Try different values in the URL such as inches.php?inches=36 or inches=12.8 TEST PAGE

Notice the way the echo statement is written: when we want to print a single quote we enclose it in double quotes and when we want to print a double quote we enclose it in single quotes.

The (int) forces the following expression to an integer value. Without this 18" would print out as 1.5'6"


INDEX, Arithmetic Operations, Order of Operations, Algebra
Next lesson: Boolean Expressions and ConditionalsMAIN INDEX
EXAMPLES INDEX

Copyright © Zebra0.com
All rights reserved worldwide.

 
 

Arithmetic Operations