There are many cases where it's useful to perform computations on numbers in PHP. As a journalist, you may need to crunch statistics that come out of a database of health code violations, for example. A school teacher might need to calculate grades by averaging test scores. A shopping site might need to total the value of items in a cart and add appropriate taxes. You might need to compare various numbers to determine the winners of a race, or to see what's most popular on your site this week. PHP includes a wealth of math-related functions to help you do this.
Here's a simple example demonstrating how to perform basic calculations:
It's fairly clear what's going on here - we assign numeric values to $a and $b, then spit them back twice in our
echo() statements - once inside a text string, then again as the result of an equation. We insert some HTML for good measure. Notice that the actual calculations are inside of parentheses - these are needed to tell PHP that you're performing math in the middle of string output.
Want to get the average of a set of numbers?
Note the placement of the parentheses - you need to establish the logical order of operations just like you did in high school. Of course, that's a pretty manual method of obtaining an average -- we've hard-coded in the list of variables and the number "3". What if we need a script that will average any number of numbers? We'll come back to that.
Let's try a more advanced calculation, and experiment with more math functions, by obtaining the value of pi and running it through the
round() function to return just three decimal places.
Another common task is to compare two numbers to see if one is larger than the other, or if they're equal or not equal. PHP includes a set of comparison operators for performing all kinds of comparisons. Comparison operators always return either "true" or "false." Truth is represented as the number 1, while falsehood is represented by ... nothing. Knowing that, try and guess what this script will return:
Was it what you expected? You should have seen a "1," then a blank line, then another "1." On line 7, we say "Tell me whether 68 is greater than 14." It is, so it's true, and the script returns "1" to represent truth. On line 8, we say "Tell me whether 14 is greater than 68." It's not, so the statement is false, so it returns nothing (you get a blank line because of the <br /> tag in the code). On line 9, we say "Tell me whether 68 is equal to 68." It is, so we get back another "1."
Notice that we used a double equal sign symbol (
==) on line 9. That symbol is used when you're testing for equality, which is very different from assigning a variable (
$a = 9).
This example may seem pretty abstract, but it will make a lot more sense when we get into conditionals in a few minutes (which will let you do things with the results of comparisons like this.)