Sort arrays
PHP has a sorting function for every shape of array: by value, by key, by a callback and under a comparison rule. The blocks below sort the same kinds of data and print the order that comes out.
Sort values
Function sort orders values from low to high and rebuilds numeric keys. Function rsort does the same in reverse order.
Copy the array first when the original order still matters later in the script.
<?php $nums = [3, 1, 2]; sort($nums); echo implode(", ", $nums), PHP_EOL;
php sort.php
1, 2, 3
The call sorts in place: there is no return value to keep, and $nums itself now holds the new order with the keys 0, 1 and 2.
Keep keys
Associative arrays pair ids with labels, so losing keys breaks the map. Function asort sorts by value while keeping each key with its value.
Function ksort sorts by key instead, which suits configs and menus ordered by name.
<?php $scores = ["bob" => 12, "ann" => 30]; asort($scores); foreach ($scores as $name => $score) { echo $name, ": ", $score, PHP_EOL; } ksort($scores); echo implode(", ", array_keys($scores)), PHP_EOL;
php assoc.php
bob: 12
ann: 30
ann, bob
The values come out low to high and every name keeps its own score; the last line shows the keys after ksort(), now in alphabetical order.
Sort with usort
Function usort lets you define the order with a callback. Return a negative number when the first item goes first and a positive number when it goes second.
The spaceship operator keeps the callback to one line and handles numbers and strings cleanly.
<?php $users = [ ["name" => "Bob", "age" => 30], ["name" => "Ann", "age" => 25], ]; usort($users, fn($a, $b) => $a["age"] <=> $b["age"]); foreach ($users as $user) { echo $user["name"], ": ", $user["age"], PHP_EOL; }
php usort.php
Ann: 25
Bob: 30
The callback compares the age field, so the younger user comes first even though Bob is the first row of the input.
Sort flags
Sort flags tune how values compare. Numeric mode treats strings as numbers while natural mode orders embedded numbers like a human would.
Use case-insensitive string mode for names so lowercase and uppercase mix evenly.
<?php $files = ["img10", "img2", "img1"]; sort($files, SORT_NATURAL); echo implode(", ", $files), PHP_EOL; $names = ["Bob", "ann"]; sort($names, SORT_FLAG_CASE | SORT_STRING); echo implode(", ", $names), PHP_EOL; $plain = ["Bob", "ann"]; sort($plain, SORT_STRING); echo implode(", ", $plain), PHP_EOL;
php flags.php
img1, img2, img10
ann, Bob
Bob, ann
Natural mode reads the numbers inside the names, so img2 comes before img10. The last two lines show the case flag at work: with it the capital B does not win over the lowercase a, and without it the byte order of SORT_STRING puts Bob first.
Exercises
- Sort a list of numbers with rsort() and print it.
- Sort a score table by value with arsort() and print the highest score first.
- Sort a list of products by price with usort() and break a tie by name.
- Sort file2, file10, file1 with and without natural mode and compare the two orders.
- Sort a list of mixed-case names case-insensitively and then byte by byte.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
sort()do to the keys of an array?Answer
It rebuilds the numeric keys from zero
sort() orders the values and numbers them again, which is why asort() exists for maps.
-
Which function sorts an associative array by value and keeps the keys?
Answer
asort()
asort() compares the values and carries each key along with its value.
-
What does a
usort()callback return when the first item should come first?Answer
A negative number
A negative result means the left item is smaller, so it is placed before the right one.
-
Which flag orders
img2beforeimg10?Answer
SORT_NATURAL
SORT_NATURAL reads the number inside the text, so 2 comes before 10 the way a person expects.
-
What does this program print?
<?php $nums = [3, 1, 2]; sort($nums); echo implode(", ", $nums);Answer
1, 2, 3
sort() orders the values from low to high in place.
-
What does this program print?
<?php $scores = ["bob" => 12, "ann" => 30]; asort($scores); echo implode(", ", array_keys($scores));Answer
bob, ann
asort() orders by value, and 12 comes before 30, so bob stays first.
-
What does this program print?
<?php $users = [ ["name" => "Bob", "age" => 30], ["name" => "Ann", "age" => 25], ]; usort($users, fn($a, $b) => $a["age"] <=> $b["age"]); echo $users[0]["name"];Answer
Ann
The callback sorts by age, so the younger Ann moves to the first position.
-
What does this program print?
<?php $files = ["img10", "img2", "img1"]; sort($files, SORT_NATURAL); echo implode(", ", $files);Answer
img1, img2, img10
Natural mode compares the numbers inside the names, so the order is 1, 2, 10.
-
What does this program print?
<?php $names = ["Bob", "ann"]; sort($names, SORT_STRING); echo implode(", ", $names);Answer
Bob, ann
Plain string order compares bytes, and the capital B is smaller than the lowercase a.
-
What does
ksort()sort by?Answer
The keys
ksort() compares the keys themselves, which suits a menu or a config ordered by name.
The code on this page was run with PHP 8.5.13 (php -v) in Alpine Linux, with the commands shown above.
Article author: Arthur Isaev