The strnatcasecmp() function compares two strings in a natural way.
PHP strnatcasecmp() Function has the following syntax.
strnatcasecmp(string1,string2)
Parameter | Is Required | Description |
---|---|---|
string1 | Required. | First string to compare |
string2 | Required. | Second string to compare |
This function returns:
In natural way, the number 2 is less than the number 10. In computer way, 10 is less than 2, because the first number in "10" is less than 2.
The strnatcasecmp() is case-insensitive.
Compare two strings using a "natural" algorithm (case-insensitive):
<?php
echo strnatcasecmp("2Hello world!","10Hello WORLD!");
echo "\n";
echo strnatcasecmp("10Hello world!","2Hello WORLD!");
?>
The code above generates the following result.
Difference between natural algorithm (strnatcmp) and regular computer string sorting algorithms (strcmp):
<?php/*www . java 2 s.c o m*/
$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.