Simple Math with PHP
Posted: February 28, 2009
PHP has built-in math functionality for most of your mathematical desires. Here are a few of the common math operators and what they do:
+ adds numbers
- subtracts
* multiplies
/ divides
% modulus (the remainder of a division)
These are pretty common and you’re probably pretty familiar with these. Though the modulus operator at the bottom may be a bit strange. It’s needed because if you divide two integers, PHP is still going to return an integer with no decimal or remainder. For example:
echo 5/2;
Would output
2
If you were to use:
echo 5%2;
You would get 1, which is the remainder of 5 divided by 2.
Notice that the numbers don’t have quotation marks around them like text does. Numbers don’t need them. If you put quotation marks around ‘2’, then it would be the string ‘2’, not the actual number 2. You can’t do math on text.
Let’s look at a few examples of using PHP for math:
$num1 = 3;
$num2 = 2;<br /><br />
echo $num1 * $num2;
outputs
6
echo $num1 - $num2;
outputs
1
echo $num2 - $num1;
outputs
-1
…and so forth.
Now, we can also assign the value of whatever mathematical operation to a variable as we’re doing it. Like so…
$total = $num1 + $num2;
echo $total;
outputs
5
Or
$total = $num1 * $num2;
outputs
6
Basically PHP will do whatever is on the right side of the equals sign first, then assign the value to the variable on the left.
Just like with Algebra, the PHP math functions do things in the ‘Order of Operations’. So multiplication and division first, then addition and subtraction, etc.
$num1 - $num2 * $num3;
would first multiply $num2 and $num3, and subtract the result from $num1. However, also just like with Algebra, you can also use parentheses to control what order things are done in. So…
($num1 - $num2) * $num3;
would first subtract $num2 from $num1, and then multiply times $num3.
There is one major difference from normal Algebra in how PHP handles math. Notice how PHP uses the equals sign to assign values to variables. PHP does not use an equals sign like we traditionally think of it, to state equivalence. That is,
$num1 = $num2;
Assigns the value of $num2 to $num1. It does not say, $num1 is equal to $num2. Or compare $num1 to $num2. To talk about the more traditional comparison we’re expecting, we use two equals signs together.
$num1 == $num2;
This tests whether the two values are equal. It’s a very common mistake to interchange these.








