Effect
|
Ascending
|
Descending
|
User-defined order
|
---|---|---|---|
Sort array by values, then reassign indices starting with
0
|
sort( )
|
rsort( )
|
usort( )
|
Sort array by values
|
asort( )
|
arsort( )
|
uasort( )
|
Sort array by keys
|
ksort( )
|
krsort( )
|
uksort( )
|
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, you'd use
this:
$names = array('cath', 'angela', 'brad', 'dave'); sort($names); // $names is now 'angela', 'brad', 'cath', 'dave'
To get them in reverse alphabetic order, simply call rsort(
) instead of sort( ).
If you have an associative array mapping usernames to minutes
of login time, you can use arsort( ) to display a table of the top
three, as shown here:
$logins = array('njt' => 415, 'kt' => 492, 'rl' => 652, 'jht' => 441, 'jj' => 441, 'wt' => 402); arsort($logins); $num_printed = 0; echo("<table>\n"); foreach ($logins as $user => $time ) { echo("<tr><td>$user</td><td>$time</td></tr>\n"); if (++$num_printed == 3) { break; // stop after three } } echo("</table>\n"); <table> <tr><td>rl</td><td>652</td></tr> <tr><td>kt</td><td>492</td></tr> <tr><td>jht</td><td>441</td></tr> </table>
ksort($logins); echo("<table>\n"); foreach ($logins as $user => $time) { echo("<tr><td>$user</td><td>$time</td></tr>\n"); } echo("</table>\n"); <table> <tr><td>jht</td><td>441</td></tr> <tr><td>jj</td><td>441</td></tr> <tr><td>kt</td><td>492</td></tr> <tr><td>njt</td><td>415</td></tr> <tr><td>rl</td><td>652</td></tr> <tr><td>wt</td><td>402</td></tr> </table>
User-defined ordering requires that you provide a function that
takes two values and returns a value that specifies the order of the two values
in the sorted array. The function should return 1 if the first value is
greater than the second, -1 if the first value is less than the second,
and 0 if the values are the same for the purposes of your custom sort
order.
a program that lets you try the various sorting functions on the same
data.