Comparison operators

Comparison operators such as <, >, and == return either a 1 or a 0 (or nothing) depending on whether the comparison was true or false, and it is this value that PHP uses to decide actions. Consider this following piece of PHP code:

<?php
    if ($foo < 10) {
        // do stuff
    }
?>

The less-than operator, <, will compare $foo to 10, and if it is less than (but not equal to) ten then < will return a 1. This will make the line read "if (1) {". As mentioned already, PHP considers 0 or nothing to be false, and anything else to be true, which means that the line reads as "if (true) {". Naturally "true" is always true, so the true block of the if statement will execute.

Now that you know how it works, you should be able to avoid a common mistake with range checking. Consider this next script:

<?php
    if ($a <= $b <= $c) {
        // do stuff
    }
?>

Here we appear to be checking that $b must be greater or equal to $a and less than or equal to $c. However, what actually happens is quite different! First, PHP compares $a with $b, and if $a is less than or equal to $b then the condition is 1, "true". However, we then find that PHP is comparing 1 against $c to see whether it is equal to or lower than it, as opposed to comparing $b against $c. This is almost certainly not what the script writer intended - the code needs to be rewritten like this:

<?php
    if ($a <= $b && $b <= $c) {
        // do stuff
    }
?>

In the modified version the two checks are kept separate, which is much better.

 

Next chapter: Complete operator list >>

Previous chapter: Shorthand unary operators

Jump to:

 

Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.