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 do I check if a variable is of array type?when i fetch the record in the database but they skip first record in the database
How do I add to the beginning of an array and find the number of elements in it?
I am not interested in the values in the arrays, how can I discard them?
How can I sort an array keeping the correlation between the index and value?
