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

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

hi, i am querying the DB as follows: $result=mysql_query("SELECT name,items FROM mytable WHERE user_id='$id'"); now,i want to create an array to insert the values that are as a result of this query e'g let's say this is the resultant data: n

How can I sort a multi-dimensional array?

I have an array of a hundred or so lines, each line has data with "|" separated values. I need to scan through this array, and select the line whose first 5 characters matches a text string. Any ideas or questions?

How do I find if a value is already in an array or not?

How can I display a 2 dimensonal array?



Custom Search