There is an entire set of operators designed to be used with the if statementthe comparison operators. In the previous chunk's example, we used the greater-than (>) operator to check the value in $minutes: <?php $minutes= 4; if($minutes > 3) { echo "Your time is up!<BR>"; echo "Please put the phone down."; $hang_up_now = TRUE; } ?> Comparison operators let you compare two values like this. All the PHP comparison operators are shown in Table 2-3.
For example, if you wanted to check whether the value in the variable $temperature was exactly 75 degrees, you could use ==, the equality operator: <?php $temperature = 75; if ($temperature == 75) { echo "75 degrees today, not too bad."; } ?> NOTE Note that the equality operator is ==, not the assignment operator, =. If you're not getting the results you want when you think you're using the equality operator in an if statement, check to make sure you haven't actually used the assignment operator instead. Here's another example, this time using the not equal operator, !=, which returns trUE if two values are not equal. In this case, we're checking to make sure that the temperature is not 75 degrees: <?php $temperature = 80; if ($temperature != 75) { echo "It's not 75 degrees today."; } ?> The results: It's not 75 degrees today. Here's an important detail about floating point precision. Internally, floating point numbers are stored in binary, not decimal, format. That means the floating point number that you think is 8.00000000 is really stored internally as 7.99999999, which is very close, but separate enough to make an equality (==) test fail. Usually, decimal values such as 1.75 or 3.12 cannot be converted into exactly the same number in the internal binary format your computer uses, which means that you can't expect to rely on floating point values down to the last digit, or even the last couple of digits, for complete precision. So how can you compare floating point numbers for equality? The easiest way is to compare them and make sure they are within a certain range. For example, say you have a value that you're using for pi: $value = 3.1415926535;. PHP comes with a built-in function named pi (see "The Math Functions" in this chapter) that will return the value of pi to fairly high precision (3.1415926535898), so we can check our value against that by checking their difference using the abs function to get the absolute value (also see "The Math Functions" in this chapter for the abs function): <?php $value = 3.1415926535; if (abs($value - pi()) < .0000001) { echo "Close enough"; } ?> |