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 non-string operands. The
== operator
casts non-string operands to
strings, so it reports that 3 and
"3" are equal. The === operator
does not cast, and returns false if the types of
the arguments differ.
$o1 = 3;
$o2 = "3";
if ($o1 == $o2) {
echo("== returns true<br>");
}
if ($o1 === $o2) {
echo("=== returns true<br>");
}
== returns trueThe
comparison
operators (<, <=, >,
>=) also work on strings:
$him = "Fred";
$her = "Wilma";
if ($him < $her) {
print "$him comes before $her in the alphabet.\n";
}
Fred comes before Wilma in the alphabetHowever, the comparison operators give unexpected results when comparing strings and numbers:
$string = "PHP Rocks";
$number = 5;
if ($string < $number) {
echo("$string < $number");
}
PHP Rocks < 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 the strcmp( )
function:
$relationship = strcmp(string_1,string_2);
The function returns a number less than 0 if
string_1 sorts before
string_2, greater than 0 if
string_2 sorts ...
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