Sort
Arrays in PHP are a powerful type with both keys and values. But they have ordering and we can thus sort them—a variety of helpful sort()
functions are available.
The sorting functions in this language have versions with different leading characters. For example, for a user-defined function sort()
, we have usort()
.
Here we see four different sorting functions. We first use sort()
, which is an ascending (low to high) sort that is probably the most commonly-used one.
usort()
for a user-defined sort. We specify an inline function that returns 0, -1 or 1 based on how any two elements are ordered.ksort()
. This acts upon the keys in an array.rsort()
function is a reverse sort. It both sorts and then reverses—it does not just reverse the ordering of the elements.// Part 1: Default sort. $values = ["z", "b", "y", "a"]; sort($values); print_r($values); // Part 2: Use usort for user-defined sort. // Specify an inline function for comparison. $values = ["aa", "bbb", "c"]; usort($values, function ($a, $b) { if (strlen($a) == strlen($b)) { return 0; } return strlen($a) < strlen($b) ? -1 : 1; }); print_r($values); // Part 3: Sort based on a key. $values = array(2 => "a", 10 => "b", 0 => "c"); ksort($values); print_r($values); // Part 4: Reverse sort. $values = [10, 50, 0]; rsort($values); print_r($values);Array ( [0] => a [1] => b [2] => y [3] => z ) Array ( [0] => c [1] => aa [2] => bbb ) Array ( [0] => c [2] => a [10] => b ) Array ( [0] => 50 [1] => 10 [2] => 0 )
Comparison
function notesConsider the usort()
function again. It requires a comparison function that receives 2 arguments, and returns 0, -1 or 1.
Sorting a, b: a same as b: 0 a before b: -1 a after b: 1
Using the simplest sorting function that works is usually the best choice. For example, if sort()
will work, using this function will lead to the clearest, most understandable code.