Comparison Operators

Comparison operators return either true or false, and thus are suitable for use in conditions. PHP has several to choose from, and they are listed in Table 6-5.

Table 6-5. The comparison operators

==

Equals

True if $a is equal to $b

===

Identical

True if $a is equal to $b and of the same type

!=

Not equal

True if $a is not equal to $b

<>

Not equal

True if $a is not equal to $b

!= =

Not identical

True if $a is not equal to $b or if they are not of the same type

<

Less than

True if $a is less than $b

>

Greater than

True if $a is greater than $b

<=

Less than or equal

True if $a is less than or equal to $b

>=

Greater than or equal

True if $a is greater than or equal to $b

Comparison operators such as <, >, and = = return true or false depending on the result of the comparison, and it is this value that PHP uses to decide actions. For example:

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

The less-than operator, <, will compare $foo to 10, and if it is less than (but not equal to) 10, then < will return true. This will make the line read if (true) {. Naturally, true is always true, so the true block of the if statement will execute.

PHP programmers prefer != to <>, despite them doing the same thing. This bias is because PHP's syntax is based on C, which uses != exclusively, and it is worth holding on to. For example, 9 <> "walrus" is true, but not because 9 is either greater or less than "walrus" as the notation <> suggests. In this example, !=

Get PHP in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.