Example: Math in PHP
In the example below, you can see how concatenation (the period symbol) is needed to perform the addition of 5 + 3 on an echo line. Then, a new variable is created called $total where 3 and 3 are added together. Using a variable, the value can be displayed in the echo statement without concatenation.
<?php
echo "<p>5 + 3</p>";
echo "<p>5 + 3 = " . (5 + 3) . "</p>";
$total = 2 + 3;
echo "<p>Total = $total</p>";
?>
Output:
5 + 3
5 + 3 = 8
Total = 5
Example: Math in PHP
<?php
$num1 = 10;
$num2 = 3;
$num3 = 4;
$total1 = $num1 - $num2;
echo "<p>5 + 2 = " . (5 + 2) . "</p>";
echo "<p>$num1 - $num2 = " . $total1 . "</p>";
echo "<p>$num1 / $num2 = " . ($num1 / $num2) . "</p>";
echo "<p>$num1 / $num2 = " . number_format(($num1 / $num2),2) . "</p>";
$total2 = 4 + 3 * 2;
$total3 = (4 + 3) * 2;
echo "<p>total2 = $total2</p>";
echo "<p>total3 = $total3</p>";
echo "<p>5 to the power of 2 = " . pow(5,2) . "</p>";
echo "<p>5 <sup>2</sup> = " . pow(5,2) . "</p>";
echo "<p>total2 * 2 = " . ($total2 * 2) . "</p>";
?>
Output:
5 + 2 = 7
10 - 3 = 7
10 / 3 = 3.33333333333
10 / 3 = 3.33
total2 = 10
total3 = 14
5 to the power of 2 = 25
5 2 = 25
total2 * 2 = 20
Example: Math operations and function
<?php
$answerAdd = 5 + 5; // equals 10
$answerMult = 5 * 5; // equals 25
$answerDiv = 5 / 5; // equals 1
$answerExp = pow(5,3); // equals 125
$answerMod = 5 % 3; // equals 2
$answerOrd = 2 + 6 * (3 + 1) ; // equals 26
echo "5+5= $answerAdd.<br>";
echo "5x5= $answerMult.<br>";
echo "5/5= $answerDiv.<br>";
echo "5 to the power of 3 = $answerExp.<br>";
echo "5 mod 3= $answerMod.<br>";
echo "2 + 6 * (3 + 1) ^ 2 = " . $answerOrd . "<br>";
?>