Sorting in php

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

EffectAscendingDescendingUser-defined order
Sort array by values, then reassign indices starting with 0sort()rsort()usort()
Sort array by valuesasort()arsort()uasort()
Sort array by keysksort()krsort()uksort()
PHP functions for sorting an array

Example of sorting in php

$logins = array(
 'njt' => 415,
 'kt' => 492,
 'rl' => 652,
 'jht' => 441,
 'jj' => 441,
 'wt' => 402,
 'hut' => 309,
$numPrinted = 0;
echo "<table>\n";
foreach ($logins as $user => $time) {
if (++$numPrinted == 3) {
 break; // stop after three
echo "</table>";

Leave a Comment