PHP » Strings » strcmp()

Syntax:
int strcmp(string s1, string s2)
s1
The first string.
s2
The second string.

Compares two strings.

The strcmp() compares two strings based on ASCII value. When the two strings are equal, zero is returned. If the first string is "smaller", in the sorting sense, -1 is returned. 1 is returned if the the first string is larger in value. This function is case sensitive.

Examples

Code:
<?php

$s1 = "abc";
$s2 = "def";
$s3 = "XYZ";

if (strcmp($s1, $s2) < 0) {
   print "$s1 is smaller than $s2<br>";
} else {
   print "$s2 is smaller than $s1<br>";
}

if (strcmp($s1, $s3) < 0) {
   print "$s1 is smaller than $s3<br>";
} else {
   print "$s3 is smaller than $s1<br>";
}

?>
Output:
abc is smaller than def
XYZ is smaller than abc
Explanation:

Note that since strcmp() is case sensitive and the ASCII value of upper case X is smaller than that of lower case a, "XYZ" is smaller than "abc".

See Also: