PHP strnatcmp() Function
The PHP strnatcmp() function is used to perform case-sensitive string comparison of two strings using a "natural order" algorithm.
Natural order sorting is considered more human-friendly than machine-oriented, pure alphabetical sorting. For example, in alphabetical sorting, "z11" would be sorted before "z2" because the "1" in the first string is sorted as smaller than "2", while in natural sorting "z2" is sorted before "z11" because "2" is treated as smaller than "11".
Alphabetical sorting:
- z11
- z2
Natural order sorting:
- z2
- z11
Syntax
strnatcmp(str1, str2)
Parameters
str1 |
Required. Specify the first string to compare |
str2 |
Required. Specify the second string to compare |
Return Value
Returns the following value:
- Returns a number less than 0, when first string is less than second string.
- Returns 0, when both strings are equal.
- Returns a number greater than 0, when first string is greater than second string.
Example:
In the example below, strnatcmp() function is used to compare two strings and returns values based on the value of two strings.
<?php //returns 0 as both strings are same echo "result1: ".strnatcmp('Hello10', 'Hello10')."\n"; //returns positive number as 11 is greater than 4 echo "result2: ".strnatcmp('Hello11', 'Hello4')."\n"; //returns negative number as 5 is less than 17 echo "result3: ".strnatcmp('Hello5', 'Hello17')."\n"; ?>
The output of the above code will be:
result1: 0 result2: 1 result3: -1
Example:
Consider one more example which demonstrates the difference between natural algorithm (strnatcmp) and regular computer string sorting algorithms (strcmp).
<?php $Arr1 = $Arr2 = array("Color15", "Color10", "Color5", "Color1"); echo "Standard string comparison\n"; usort($Arr1, "strcmp"); print_r($Arr1); echo "\nNatural order string comparison\n"; usort($Arr2, "strnatcmp"); print_r($Arr2); ?>
The output of the above code will be:
Standard string comparison Array ( [0] => Color1 [1] => Color10 [2] => Color15 [3] => Color5 ) Natural order string comparison Array ( [0] => Color1 [1] => Color5 [2] => Color10 [3] => Color15 )
❮ PHP String Reference