Main Content

PHP and natural sorting

Archive - Originally posted on "The Horse's Mouth" - 2004-09-19 10:01:47 - Graham Ellis

If you sort (8, 9, 10, 11, 12), how do you want them to be output? "In the order you've just listed, Graham", you'll probably say. But if they're strings and you sort them, then you'll get the order 10, 11, 12, 8, 9 output if you just use a default sort, because the character "1" comes before the character "8" in the alphabet.

Using PHP, you could write your own sort routine (using usort) ... but there's a better way - a function called "natsort". Remember the PHP rule of thumb - if you think surely someone's done that before then often the solution will be there's a function to do that.

Here's an example of the output from an illustrative program:

Original
0 .. 12 Drummers Drumming
1 .. 7 Swans a'Swimming
2 .. 11 Pipers Piping
3 .. 9 Ladies Dancing
4 .. 10 Lords a'Leaping
5 .. 8 Maid a'Milking
Default Sort
0 .. 10 Lords a'Leaping
1 .. 11 Pipers Piping
2 .. 12 Drummers Drumming
3 .. 7 Swans a'Swimming
4 .. 8 Maid a'Milking
5 .. 9 Ladies Dancing
Numeric sort
0 .. 7
1 .. 8
2 .. 9
3 .. 10
4 .. 11
5 .. 12
Natural Sort
1 .. 7 Swans a'Swimming
5 .. 8 Maid a'Milking
3 .. 9 Ladies Dancing
4 .. 10 Lords a'Leaping
2 .. 11 Pipers Piping
0 .. 12 Drummers Drumming

This program can be run from here and you can view the source code here.