Comparing Strings
PHP has two operators and six functions for comparing strings to each other.
Exact Comparisons
You can compare two strings for equality with the == and ===
operators. These operators differ in how they deal with nonstring
operands. The == operator casts
string operands to numbers, so it reports that 3 and "3"
are equal. Due to the rules for casting strings to numbers, it would
also report that 3 and "3b" are equal, as only the portion of the
string up to a non-number character is used when casting it. The
=== operator does not cast, and
returns false if the data types of
the arguments differ:
$o1=3;$o2="3";if($o1==$o2){echo("== returns true<br>");}if($o1===$o2){echo("=== returns true<br>");}==returnstrue
The comparison operators (<, <=, >, >=) also work on strings:
$him="Fred";$her="Wilma";if($him<$her){"{$him}comes before{$her}in the alphabet.\n";}FredcomesbeforeWilmainthealphabet
However, the comparison operators give unexpected results when comparing strings and numbers:
$string="PHP Rocks";$number=5;if($string<$number){echo("{$string}<{$number}");}PHPRocks<5
When one argument to a comparison operator is a number, the other
argument is cast to a number. This means that "PHP Rocks" is cast to a number, giving
0 (since the string does not start
with a number). Because 0 is less than 5, PHP prints "PHP Rocks <
5".
To explicitly compare two strings as strings, casting numbers to strings if necessary, use ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access