4.7.15 Comparing strings: strcmp() and strcasecmp()This is NOT the latest copy of this book; click here for the latest version.
int strcmp ( string str1, string str2)
int strcasecmp ( string str1, string str2)
Strcmp(), and its case-insensitive sibling strcasecmp(), is a quick way of comparing two words and telling whether they are equal, or whether one comes before the other. It takes two words for its two parameters, and returns -1 if word one comes alphabetically before word two, 1 if word one comes alphabetically after word two, or 0 if word one and word two are the same.
<?php
$string1 = "foo";
$string2 = "bar";
$result = strcmp($string1, $string2);
switch ($result) {
case -1: print "Foo comes before bar"; break;
case 0: print "Foo and bar are the same"; break;
case 1: print "Foo comes after bar"; break;
} ?>
It is not necessary for us to see that "foo" comes after "bar" in the alphabet because we already know it does, however you would not bother running strcmp() if you already knew the contents of the strings - it is most useful when you get unknown input and you want to sort it.
As you can see, strcmp() can serve in place of == because it returns 0 when two strings are equal. There is an urban myth amongst PHP programmers that == is faster than strcmp(), however the reality is that it is just as fast, and you can use the two interchangeably if you wish. One thing, though: using ==, you get a "1" if two strings match, whereas with strcmp() you get a 0, so be careful!
|
Want to see this stuff in print? PHP in a Nutshell takes the core topics covered here, adds in thousands of edits from the editorial team and myself, and combines them to make an unbeatable reference for PHP programmers at all levels.
My latest book has hundreds more tips on how to use PHP, Apache, and MySQL, plus Perl, Python, shell scripts, performance tuning, and more!
|