Home > Article > Backend Development > "Natural" ordering of PHP arrays_PHP Tutorial
natsort
(PHP 4, PHP 5)
natsort — Sort an array using the "natural sorting" algorithm
Description
bool natsort (array &$array)
This function implements a sorting algorithm in the same way that people normally sort alphanumeric strings and maintains the original key/value association. This is called "natural sorting". The difference between this algorithm and the usual computer string sorting algorithm (used in sort()) is shown in the example below.
Parameters
array
input array.
Return value
Returns TRUE on success, or FALSE on failure.
Example #1 natsort() examples demonstrating basic usage
$array1 = $array2 = array("img12.png", "img10.png", "img2.png", "img1.png");
asort($array1);
echo "Standard sortingn";
print_r($array1);
natsort($array2);
echo "nNatural order sortingn";
print_r($array2);
?>
The above routine will output:
Standard sorting
Array
(
[3] => img1.png
[1] => img10.png
[0] => img12.png
[2] => img2.png
)
Natural order sorting
Array
(
[3] => img1.png
[2] => img2.png
[1] => img10.png
[0] => img12.png
)