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.
The functions provided by PHP to sort an array are shown in Table 5-1.
Table 5-1. PHP functions for sorting an array
Sort array by values, then reassign indices starting with 0
Sort array by values
Sort array by keys
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
To sort names into ascending alphabetical order, do something like this: