Sorting
Sorting changes the internal order of elements in an array and optionally rewrites the keys to reflect this new order. For example, you might use sorting to arrange a list of scores from biggest to smallest, to alphabetize a list of names or to order a set of users based on how many messages they posted.
PHP provides three ways to sort arrays—sorting by keys, sorting by values without changing the keys, or sorting by values and then changing the keys. Each kind of sort can be done in ascending order, descending order, or an order determined by a user-defined function.
Sorting One Array at a Time
The functions provided by PHP to sort an array are shown in Table 5-1.
Table 5-1. PHP functions for sorting an array
Effect | Ascending | Descending | User-defined order |
---|---|---|---|
Sort array by values, then reassign indices starting with 0 |
|
|
|
Sort array by values |
|
|
|
Sort array by keys |
|
|
|
The sort()
, rsort()
, and usort()
functions are designed to work on
indexed arrays because they assign new numeric keys to represent the
ordering. They’re useful when you need to answer questions such as “What
are the top 10 scores?” and “Who’s the third person in alphabetical
order?” The other sort functions can be used on indexed arrays, but
you’ll only be able to access the sorted ordering by using traversal
functions such as foreach
and
next
.
To sort names into ascending alphabetical order, do something like this:
$names
=
array
(
"Cath"
,
"Angela"
,
"Brad"
,
"Mira"
);
sort ...
Get Programming PHP, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.