PHP natsort() Function
Example
Sort the array:
<?php $temp_files = array("temp15.txt","temp10.txt", "temp1.txt","temp22.txt","temp2.txt"); sort($temp_files); echo "Standard Sorting:"; print_r($temp_files); echo "<br>"; natsort($temp_files); echo "Natural Sorting:"; print_r($temp_files); ?>
Definition and Usage
The natsort() function sorts the array using the 'natural sorting' algorithm. The keys retain their original key names.
In natural sorting algorithms, the number 2 is less than the number 10. In computer sorting algorithms, 10 is less than 2 because the first digit in '10' is less than 2.
Syntax
natsort(array)
Parameter | Description |
---|---|
array | Required. Specifies the array to be sorted. |
The natsort() function sorts the elements in the given array using the natural order algorithm.
The natsort() function implements 'natural sorting', which is the sorting method of numbers from 1 to 9, letters from a to z, and shorter ones have priority. The indices of the array are associated with the unit values.
If successful, the function returns TRUE, otherwise FALSE.
Technical Details
Return Value: | Returns TRUE on success, FALSE on failure. |
PHP Version: | 4+ |
Update Log: | Starting from PHP 5.2.10, when 0 is used to fill numeric strings (e.g., '00006'), 0 will be ignored. |