The strnatcmp() function compares two strings in a natural way.
In a natural algorithm, the number 2 is less than the number 10. In computer sorting, 10 is less than 2, because the first number in "10" is less than 2.
PHP strnatcmp() Function has the following syntax.
strnatcmp(string1,string2)
Parameter | Is Required | Description |
---|---|---|
string1 | Required. | First string to compare |
string2 | Required. | Second string to compare |
This function returns:
Compare two strings using a "natural" algorithm (case-sensitive):
<?php
echo strnatcmp("2Hello world!","10Hello world!");
echo "\n";
echo strnatcmp("10Hello world!","2Hello world!");
?>
The code above generates the following result.
Difference between natural algorithm (strnatcmp) and regular computer string sorting algorithms (strcmp):
<?php//from w w w . java 2 s . c om
$arr1 = $arr2 = array("PHP1","PHP2","PHP10","PHP01","PHP100","PHP20","PHP30","PHP200");
echo "Standard string comparison"."\n";
usort($arr1,"strcmp");
print_r($arr1);
echo "\n";
echo "Natural order string comparison"."\n";
usort($arr2,"strnatcmp");
print_r($arr2);
?>
The code above generates the following result.