Sorting in php 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
Table of PHP functions for sorting an array
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() |
Example of sorting in php
$logins = array(
'njt' => 415,
'kt' => 492,
'rl' => 652,
'jht' => 441,
'jj' => 441,
'wt' => 402,
'hut' => 309,
);
arsort($logins);
$numPrinted = 0;
echo "<table>\n";
foreach ($logins as $user => $time) {
echo("<tr><td>{$user}</td><td>{$time}</td></tr>\n");
if (++$numPrinted == 3) {
break; // stop after three
}
}
echo "</table>";