Natural comparison of two strings.
When strings contain numbers, strcmp() often gives an undesired ordering. For example, "document2" would be larger than "document10" with strcmp(). strnatcmp() is the answer to this problem. 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.
<?php
$s1 = "document10";
$s2 = "document2";
print "With strnatcmp():<br>";
if (strnatcmp($s1, $s2) < 0) {
print "$s1 is smaller than $s2<br>";
} else {
print "$s2 is smaller than $s1<br>";
}
print "<br>With strcmp():<br>";
if (strcmp($s1, $s2) < 0) {
print "$s1 is smaller than $s2<br>";
} else {
print "$s2 is smaller than $s1<br>";
}
?>
With strnatcmp():
document2 is smaller than document10
With strcmp():
document10 is smaller than document2
This code demonstrates the difference between strnatcmp() and strcmp().