Name
strcmp()
Synopsis
int strcmp ( stringstr1, stringstr2)
The strcmp() function, 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.
$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.
If the only difference between your strings is the capitalization of letters, you should know that capital letters come before their lowercase equivalents. For example, "PHP" will come before "php."