PHP Questions Home

Categories

Arrays
Files
Forms
Functions
Images
MySQL
Numbers
Others
Strings
Website


PHP Functions

PHP Functions


More PHP

Top Questions
Ask a Question

How do I sort alphanumeric array data correctly?


A human would often sort alphanumeric strings differently to the default functions in a computer language.

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.



More arrays PHP Questions

How can I sort an array keeping the correlation between the index and value?
How do I write my own sort function?
How do you remove duplicate values from an array?
How do I find the size of an array?
I am not interested in the values in the arrays, how can I discard them?