PHP has 11 different built-in sorting options as of this writing and the manual, though offering good examples of how to use most of them, doesn’t really put them all on one single, quick summarized reference page. Here’s my attempt at doing just that.
sort - sort alphabetically (a-z) or numerically (0-9)
rsort - sort reverse-alphabetically (z-a) or numericall (9-0)
asort - sort alphabetically or numerically, maintain $array indices, used for associative arrays
arsort - sort reverse-alphabetically (z-a) or numerically (9-0), maintain $array indices, used for associative arrays
array_multisort (PHP 4, 5) - sort mult-dimensional or multiple arrays, numeric keys will be re-indexed but strings will be maintained.
Sorting ORDER flags: sort_asc (default) - sort in ASCending (a-z, 0-9) order
sort_desc - sort in DESCending order (z-a, 9-0)
Sorting TYPE flags: sort_regular (default)
sort_numeric - compare items numerically
sort_string - compare items as string
ksort - sort array alphabetically or numerically by keys, used for associative arrays
krsort - sort array reverse-alphabetically (z-a) or numerically (9-0) by keys, used for associaative arrays
natsort (PHP 4, 5) - case sensitive sort using human natural sorting, useful for sorting things like upper or lower (but not mixed) filenames with strings and numbers
natcasesort (PHP 4, 5) - case INsensitive sort using human natural sorting, useful for sorting things like mixed case filenames with strings and numbers
uasort - sort array with a user-defined comparison function and maintain index association
uksort - sort array by keys using a user-defined comparison function, useful if no other available sorts apply like sorting objects
An additional function that might come in handy once sorting some arrays like the natsort is array_reverse (PHP 4, 5) which will take the contents of an array and return them reverse. For example, I needed to sort the following data:
ref_08_2005
ref_09_2005
ref_10_2005
so that it would appear in a dropdown SELECT menu like this:
ref_10_2005
ref_09_2005
ref_08_2005
This was accomplished by using the following code:
<?php
$unsorted =
array( ‘ref_08_2005′,
‘ref_09_2005′,
‘ref_10_2005′);
array_reverse($unsorted);
foreach($unsorted as $each) {
print “$each<br />”;
}
/* 11 sorting functions PHP manual links
http://php.net/sort
http://php.net/rsort
http://php.net/asort
http://php.net/arsort
http://php.net/array_multisort
http://php.net/ksort
http://php.net/krsort
http://php.net/natsort
http://php.net/natcasesort
http://php.net/uasort
http://php.net/uksort
*/
?>
Over time the plan is to update and refine this PHP sorting reference based on comments/feedback and future research so please use the comments area to help improve this information and keep it relevant timely. This one, if you like, might be good for a bookmark.