OK, let’s take a look at calculations, another crucial part of PHP.


Let’s look at this example:
<?php
$n1 = 14;
$n2 = 16;
$total = $n1 + $n2;
echo $n1.” plus “.$n2.” equals “.$total;
?>
The output: “14 plus 16 equals 30″
You see there’s nothing to it. Just put the numbers (or variables) which you want to use in a calculation in a variable.
The operators below can be used to make calculations:
- + (example above)
- – (example: $number = 100 – 50 – 20;)
- *: multiply (example: $number = 5 * 10;)
- /: divide (example: $number = 10 / 5;)
- %: modulo (some of you will not know this one. An example: 11 % 5 = 1, because when you divide 11 with 5, you get 2 and the rest is 1. Another example: 23 % 10 = 3.)
Here are some examples of easier calculations:
$i++;    //This is equal to: $i = $i + 1;
$i–;       //This is equal to: $i = $i – 1;
$i *= 3 //This is equal to: $i = $i * 3;
$i += 5//This is equal to: $i = $i + 5;
Another example: square root
<?php
$number = 9;
$root = sqrt($number);
echo “The square root of “.$number.” is “.$root;
?>
The output: “The square root of 9 is 3″
The way to calculate was a bit different than with + for example. That is because PHP calculates the square root with a function, and the variable $number (value 9) was its input. I’ll tell you much more about functions later on, and I’ll also tell you how to make your own functions.
OK, this is the end of part 3. Leave some feedback if you found this useful (or didn’t get it at all).