Welcome to PHP
An Intranet Design
Magazine Tutorial
By Aaron Weiss
PHP Comparison Operators
| Operator |
Name |
Description |
Examples |
Yields |
==
|
Equality |
Tests whether two expressions are of equal value. For strings,
the two must be exactly the same. |
$val1 == $val2
$name1 == $name2
|
false
false
|
!=
|
Inequality |
Tests whether two expressions are not equal, or for strings,
not exactly the same. |
$val1 != $val2
$name1 != $name2
|
true
true
|
<
|
Less than |
Tests whether the lefthand expression has a value smaller
than the righthand expression. For strings, smaller means "comes before
alphabetically". |
$val1 < $val2
$name1 < $name2
|
false
true
|
>
|
Greater than |
Tests whether the lefthand expression has a value greater
than the righthand expression. For strings, greater means "comes after
alphabetically". |
$val1 > $val2
$name1 > $name2
|
true
false
|
<=
|
Less than or equal to |
Tests whether the lefthand expression is of equal or lesser
value than the righthand expression. |
$val1 <= 15
$name1 <= "Martin"
|
true
true
|
>=
|
Greater than or equal to |
Tests whether the lefthand expression is of equal or greater
value than the righthand expression. |
$val2 >=6
$name2 >= "Manfred"
|
true
true
|
Let's raise the stakes: comparing two values is one thing, but sometimes you
need something more, such as the ability to compare several comparisons! Let's
be logical about this, and use PHP's logical operators.
Suppose for example that you need to know whether $val1 is of lesser
value than $val2, and also whether $name1 is of greater
value than $name2.
Remember that each comparison expression yields a true or false value. For
the record, PHP does not actually possess true or false values, known as boolean
data types. Rather, PHP considers the numeric value zero (0), or the string
values "0" or empty "" to be false. Any other value, such
as 1, or 3, or "cat", is considered to be true. A logical operator
compares these true or false values. For example, using PHP's and logical
operator:
($val1 < $val2) and ($name1 > $name2)
Because this code fragment is not a full statement, there is no closing semicolon.
Rather, we see parentheses grouping two expressions. The lefthand expression
will evaluate to the value false, if we assume the example values used in the
comparison operator table. The righthand expression
will also be false, since "Martin" does not come after "Michael"
alphabetically. The and operator will therefore compare the values "false
and false". Because this operator returns true only when both expressions
are true, the above expression will ultimately return false. That can be hard
to follow, so let's look at a summary table.
PHP Logical Operators >
< Operations and Comparisons