How do I sort alphanumeric array data correctly?
Therefore, when you want to sort such items as a human may, it is often referred to as natural sorting.
For instance, look at this output:
<?php
$numbers = array("1.gif","2.gif","20.gif","10.gif");
sort($numbers);
print_r($numbers);
?>
Array
(
[0] => 1.gif
[1] => 10.gif
[2] => 2.gif
[3] => 20.gif
)
If you were sorting the filenames in order, you would put 1.gif, 2.gif with 10.gif and 20.gif coming later. However the default sort algorithm doesn't do this, as you can see.
So if you want to sort in 'natural order' then you're in luck, because PHP provides the natsort function to save you having to write a clever function yourself, and this will do just what you want here:
<?php
$numbers = array("1.gif","2.gif","20.gif","10.gif");
natsort($numbers);
print_r($numbers);
?>
Which this time prints just what we're after:
Array
(
[0] => 1.gif
[1] => 2.gif
[3] => 10.gif
[2] => 20.gif
)
Note how it also maintains the keys, which is also often invaluable.
Comments on this Question/Answer
Natsort will sort while maintaining the keys, is there a way of doing the same sort without maintaining the keys?By: Dave Rigby, 25 Apr 2009 18:03:06
Reply to comments / post your own comment >>>
ASK A QUESTION
More arrays PHP Questions
How can I sort an array keeping the correlation between the index and value?How do I change: function wordlimit($string, $length = 50, $ellipsis = "...") { $words = explode(' ', strip_tags($string)); if (count($words) > $length) return implode(' ', array_slice($words, 0, $length)) . $ellipsis; else
How can I check if a value is already in an array?
How do we sort an array of names taken from a text file, displaying only unique names?
How can I create an array of numbers easily?
