The strcmp() function is used to compare two case-sensitive strings. This function was introduced in PHP3. The function basically compares two strings; returns a number less than 0 if one is less than two, 0 if the two strings are equal, and a number greater than 0 if one is greater than two. The comparison is case-sensitive—that is, “Alphabet” and “alphabet” are not considered equal.
Syntax:
strcmp(string $string1, string $string2): int
Parameters
Parameter | Description |
---|---|
string1 | The first string. |
string2 | The second string. |
Return Values
Returns 0 if string1 is greater than string2, and 0 if they are equal.
Examples
Example 1:
$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; }
Example 2:
<?php $var1 = "Hello"; $var2 = "hello"; if (strcmp($var1, $var2) !== 0) { echo '$var1 is not equal to $var2 in a case sensitive string comparison'; } ?>
Final Thoughts
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 afterword two, or 0 if word one and word two are the same.