Sort an array using natsort() for natural order sorting and natcasesort() for case-insensitive natural order sorting.
| <?php $temp_files = array(“temp15.txt”,“Temp10.txt”, “temp1.txt”,“Temp22.txt”,“temp2.txt”); natsort($temp_files); echo “Natural order: “; print_r($temp_files); echo “<br />”; natcasesort($temp_files); echo “Natural order case insensitve: “; print_r($temp_files); ?> |
The result of the code above will be:
| Natural order: Array ( [0] => Temp10.txt [1] => Temp22.txt [2] => temp1.txt [4] => temp2.txt [3] => temp15.txt ) Natural order case insensitve: Array ( [2] => temp1.txt [4] => temp2.txt [0] => Temp10.txt [3] => temp15.txt [1] => Temp22.txt ) |
The natcasesort() function sorts an array using a “natural order” algorithm, where the values retain their original keys.
In natural order, the number 2 is considered less than the number 10, unlike in standard computer sorting where 10 is considered less than 2 due to the numerical comparison of characters.
This function performs case-insensitive sorting.
| natcasesort(array) |
|
Parameter |
Description |
|
array |
Required. Specifies the array to be sorted |
|
Return Value: |
Returns TRUE on success or FALSE on failure |
|
PHP Version: |
4+ |