PHP Questions Home | Register | Login
Categories
Arrays
Files
Forms
Creating PDFs
PHP Errors
Functions
Images
MySQL
Numbers
Others
Strings
Website
Unanswered

PHP Forums
Forums Index
MySQL Forum
PHP Forum
Flash/Actionscript
Javascript
Web design

More PHP
PHP Functions
Top Questions
Ask a Question
PHP Interview Questions
PHP Jobs
Ecommerce
IT Questions
Business Websites

Sponsors

sponsor ad
My Salary
PHP Developer Salary
Advertise Here

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.

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 return all the values in an array?

How do I remove and view the last element of an array?

Hi. i have a music samples website. in one table, id like a different sample to appear every time the page is refreshed. how do i acheve this? how can i alterate and retrieve these bloody mp3's? surely i can use a PHP script? thankyou

How do I remove an element from an array without changing the index values for the rest of the array?

I have the following list : Tom T1 Tom T2 Bill T1 Bill T2 Jack T1 Jack T2 I need it converted into : Tom T1,T2 Bill T1,T2 Jack T1,T2



Custom Search