Home
PHP
sort Examples (usort, ksort)
This page was last reviewed on May 26, 2023.
Dot Net Perls
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."
Example. Here we see 4 different sorting functions. We first use sort(), which is an ascending (low to high) sort that is probably the most commonly-used one.
Step 1 We sort a 4-element array that we declared with short array syntax. It has strings, so we get "a" before "z."
array
Step 2 We use usort for a user-defined sort. We specify an inline function that returns 0, -1 or 1 based on how any 2 elements are ordered.
Step 3 For a key-based sort, we invoke ksort(). This acts upon the keys in an array.
Step 4 The rsort 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 notes. Consider the usort() function again. It requires a comparison function that receives 2 arguments, and returns 0, -1 or 1.
Note For 2 items that are equal in sorting order, the value 0 must be returned.
And If the first argument should come before the second, we return -1, and if after, we return 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on May 26, 2023 (image).
Home
Changes
© 2007-2024 Sam Allen.