To multiply in PHP (and just about every other programming language), the * symbol is used. If you see 20 * 10, it means multiply 20 by 10. Here's some code for you to try:
<?php
$first_number = 10;
$second_number = 20;
$sum_total = $second_number * $first_number;
$second_number = 20;
$sum_total = $second_number * $first_number;
print ($sum_total);
?>
In the above code, we're just multiplying whatever is inside of our two variables. We're then assigning the answer to the variable on the left of the equals sign. (You can probably guess what the answer is without running the code!)
Just like addition and subtraction, you can multiply more than two numbers:
<?php
$first_number = 10;
$second_number = 20;
$third_number = 100;
$second_number = 20;
$third_number = 100;
$sum_total = $third_number * $second_number * $first_number;
print ($sum_total);
?>
And you can even do this:
$sum_total = $third_number * $second_number * 10;
But try this code. See if you can guess what the answer is before trying it out:
<?php
$first_number = 10;
$second_number = 2;
$third_number = 3;
$second_number = 2;
$third_number = 3;
$sum_total = $third_number + $second_number * $first_number;
print ($sum_total);
?>
What answer did you expect? If you were expecting to get an answer of 50 then you really need to know about operator precedence! As was mentioned, some operators (Math symbols) are calculated before others in PHP. Multiplication and division are thought to be more important that addition and division. So these will get calculated first. In our sum above, PHP sees the * symbol, and then multiplies these two numbers first. When it works out the answer, it will move on to the other symbol, the plus sign. It does this first:
$second_number * $first_number;
Then it moves on to the addition. It doesn't do this first:
$third_number + $second_number
This makes the parentheses more important than ever! Use them to force PHP to work out the sums your way. Here's the two different version. Try them both:
Version one
$sum_total = $third_number + ($second_number * $first_number);
$sum_total = $third_number + ($second_number * $first_number);
Version two
$sum_total = ($third_number + $second_number) * $first_number;
$sum_total = ($third_number + $second_number) * $first_number;
Here's we're using parentheses to force two different answers. PHP will work out the sum between the parentheses first, and then move on to the other operator. In version one, we're using parentheses to make sure that PHP does the multiplication first. When it gets the answer to the multiplication, THEN the addition is done. In version two, we're using parentheses to make sure that PHP does the addition first. When it gets the answer to the addition, THEN the multiplication is done.
No comments:
Post a Comment