Math Arithmetic Operators in PHP
Arithmetic operators are operators that we use for mathematical operations. In addition to the four operations (addition, multiplication, division, subtraction) in mathematics, we also use one to get the mode (remainder).
A summary of the use of arithmetic operators is shown in the table below.
+ Addition $x + $y Adds the values $x and $y.
- Subtraction $x - $y Subtracts $x from $y.
* Multiply $x * $y The value of $x is multiplied by the value of $y.
/ Division $x / $y Divide $x by $y.
% Mod (Remainder) $x % $y Divide $x by $y to find the remainder.
Addition Operator (+)
It is used to add two or more values. For example;
<?php
echo 10 + 5; // Output: 15
?>
It can also be summed in values assigned to variables.
<?php
$x = 5;
$y = 10;
echo $x + $y;
?>
It is used to subtract two or more values. For example;
<?php
echo 10 - 5; // Output: 5
?>
Multiplication Operator (*)
It is used to multiply two or more values. For example;
<?php
echo 10 * 5; // Output: 50
?>
Division Operator (/)
It is used to divide two or more values. For example;
<?php
echo 10 / 2; // Output: 5
?>
Mod (Remainder) Operator (%)
It is used to find the remainder from the division of two or more values. For example;
<?php
echo 10 3%; // Output: 1
?>
Using All Operators Together
Let's make it more meaningful with an example that uses 5 arithmatic operators together.
<?php
$a = 7;
$b = 5;
$c = 9;
$d = 4;
$e = 3;
echo $a + $b - $c + $a / $d % $e; // Output: 4
?>
Parenthesis Priority
In the example where we use all operators, we do not use parentheses, so there is no meaningful result. Let's repeat the same example, using parentheses to indicate process priorities;
<?php
$a = 7;
$b = 5;
$c = 9;
$d = 4;
$e = 3;
echo (($a + $b) - (($c + $a) / $d)) % $e; // Output: 2
?>
Here we first do the operations in the first parenthesis before finding the remainder. First we find the value of 12 by saying $a + $b, and by saying ($c + $a) / $d we find the value 4.
Then we subtract 4 from 12 and get the mod (remainder) of 8. The result is 2 out of 8 3%.
<?php
echo ((7 + 5) - ((9 + 7) / 4)) 3%; // Output: 2
?>
To make this more meaningful, let's see the math operation using direct numbers instead of variable values.