Arithmetic operators are used to perform mathematical operations. Following table summarizes the arithmetic operators.
Operator |
Name |
Example |
Description |
- |
Negation |
-$a |
Opposite of $a. |
+ |
Addition |
$a + $b |
Sum of $a and $b |
- |
Subtraction |
$a - $b |
Difference of $a and $b |
* |
Multiplication |
$a * $b |
Multiplication of $a and $b |
/ |
Division |
$a / $b |
Quotient of $a and $b. |
% |
Modulo |
$a % $b |
Remainder of $a divided by $b. |
** |
Exponentiation |
$a ** $b |
Result of raising $a to the $b'th power. |
arithmetic_operators_demo.php
#!/usr/bin/php
<?php
$a = 20;
$b = 11;
$c = - $a;
$d = $a + $b;
$e = $a - $b;
$f = $a * $b;
$g = $a / $b;
$h = $a % $b;
$i = $a ** 2;
echo "Negation of $a is $c\n";
echo "Sum of $a and $b is $d\n";
echo "Difference of $a and $b is $e\n";
echo "Multiplication of $a and $b is $f\n";
echo "Division of $a and $b is $g\n";
echo "Modulo of $a and $b is $h\n";
echo "$a square is $i\n";
?>
Output
$./arithmetic_operators_demo.php
Negation of 20 is -20
Sum of 20 and 11 is 31
Difference of 20 and 11 is 9
Multiplication of 20 and 11 is 220
Division of 20 and 11 is 1.8181818181818
Modulo of 20 and 11 is 9
20 square is 400
Php follows PEDMAS rule while evaluating Arithmetic expressions. PEDMAS is an acronym for Parenthesis, Exponential, Multiplication, Division, Addition and Subtraction.
As per PEDMAS rule,
a. PHP perform the operations inside a parenthesis first
b. Then exponents
c. Then multiplication and division, from left to right
d. Then addition and subtraction, from left to right
Example 1: 10 + 2 * 3
Since * has more priority than +, 2 * 3 will be evaluated first.
10 + 2 * 3 = 10 + 6 = 16.
Example 2: 10 + 2 * (5 - 2) * 6
Since parenthesis has greater priority, expression inside the parenthesis will be evaluated first, then multiplication operations from left to right.
10 + 2 * (5 - 2) * 6 = 10 + 2 * 3 * 6
= 10 + 6 * 6
= 10 + 36
= 46
pedmas_demo.php
#!/usr/bin/php
<?php
$result1 = 10 + 2 * 3;
$result2 = 10 + 2 * (5 - 2) * 6;
echo "\$result1 : $result1\n";
echo "\$result2 : $result2";
?>
Output
$./pedmas_demo.php
$result1 : 16
$result2 : 46
Note
Operands of modulo are converted to integers before processing. For floating-point modulo, use fmod() function.
No comments:
Post a Comment