Subtraction in PHP

 

We're not going to weigh things down by subjecting you to torrents of heavy Math! But you do need to know how to use the basic operators. First up is subtracting.

 

To add up using PHP variables, you did this:

<?php

$first_number = 10;
$second_number = 20;
$sum_total = $first_number + $second_number;

print ($sum_total);

?>

Subtraction is more or less the same. Instead of the plus sign (+), simply use the minus sign (-). Change your $sum_total line to this, and run your code:

$sum_total = $second_number - $first_number;

The s$sum_total line is more or less the same as the first one. Except we're now using the minus sign instead (and reversing the two variables). When you run the script you should, of course, get the answer 10. Again, PHP knows what is inside of the variables called $second_number and $first_number. It knows this because you assigned values to these variables in the first two lines. When PHP comes across the minus sign, it does the subtraction for you, and puts the answer into the variable on the left of the equals sign. We then use a print statement to display what is inside of the variable.

Just like addition, you can subtract more than one number at a time. Try this:

<?php

$first_number = 10;
$second_number = 20;
$third_number = 100;

$sum_total = $third_number - $second_number - $first_number;

print ($sum_total);

?>

The answer you should get is 70. You can also mix addition with subtraction. Here's an example:

<?php

$first_number = 10;
$second_number = 20;
$third_number = 100;

$sum_total = $third_number - $second_number + $first_number;

print ($sum_total);

?>

Run the code above. What answer did you get? Was it the answer you were expecting? Why do you think it printed the number it did? If you thought it might have printed a different answer to the one you got, the reason might be the way we set out the sum. Did we mean 100 - 20, and then add the 10? Or did we mean add up 10 and 20, then take it away from 100? The first sum would get 90, but the second sum would get 70.

To clarify what you mean, you can use parentheses in your sums. Here's the two different versions of the sum. Try them both in your code. But note where the parentheses are:

Version one
$sum_total = ($third_number - $second_number) + $first_number;

Version two
$sum_total = $third_number - ($second_number + $first_number);

It's always a good idea to use parentheses in your sums, just to clarify what you want PHP to calculate. That way, you won't get a peculiar answer!

Another reason to use parentheses is because of something called operator precedence. In PHP, some operators (Math symbols) are calculated before others. This means that you'll get answers that are entirely unexpected! As we'll find out right now in the next part - Multiplication.