Home
PHP
sort Examples
Updated Jun 30, 2025
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 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 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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Jun 30, 2025 (edit).
Home
Changes
© 2007-2025 Sam Allen