TExcelTAD
Home › PHP › PHP Sorting Arrays

PHP Sorting Arrays

PHP ships with a whole family of sort functions. They all sort the array in place (they change the variable you pass and return true), and they differ in three ways: what they compare (values or keys), the direction, and whether they keep the keys.

The sort family at a glance

Function Sorts by Order Keeps key → value pairs?
sort() value ascending no — re-numbers 0, 1, 2…
rsort() value descending no
asort() value ascending yes
arsort() value descending yes
ksort() key ascending yes
krsort() key descending yes
usort() value, your function custom no
uasort() value, your function custom yes
uksort() key, your function custom yes

An easy way to remember: a = associative (keep keys), k = by key, r = reverse, u = user function.

Sorting simple lists

php · try it yourself
<?php
$numbers = [42, 7, 19, 3, 25];
sort($numbers);
echo implode(', ', $numbers) . PHP_EOL;

rsort($numbers);
echo implode(', ', $numbers) . PHP_EOL;

$words = ['pear', 'apple', 'Banana', 'cherry'];
sort($words);
echo implode(', ', $words) . PHP_EOL;

sort($words, SORT_FLAG_CASE | SORT_STRING);
echo implode(', ', $words) . PHP_EOL;
3, 7, 19, 25, 42
42, 25, 19, 7, 3
Banana, apple, cherry, pear
apple, Banana, cherry, pear

By default strings are compared byte by byte, so uppercase letters come before lowercase ones ('Zebra' sorts before 'apple'). The flag SORT_FLAG_CASE | SORT_STRING makes the comparison case-insensitive.

Note: The sort functions return true, not the sorted array. Writing $sorted = sort($list); is a common beginner bug — $sorted becomes true.

Keeping keys: asort and ksort

With associative arrays you almost always want to keep each key attached to its value. sort() would throw the keys away.

php · try it yourself
<?php
$scores = ['Nam' => 72, 'Eva' => 95, 'Tom' => 88];

asort($scores);
print_r($scores);

arsort($scores);
echo 'Winner: ' . array_key_first($scores) . PHP_EOL;

ksort($scores);
echo implode(', ', array_keys($scores)) . PHP_EOL;
Array
(
    [Nam] => 72
    [Tom] => 88
    [Eva] => 95
)
Winner: Eva
Eva, Nam, Tom

Custom order with usort

For anything more complex — sorting records by a field, or by several fields — pass a comparison function. It receives two items and returns a negative number if the first should come first, a positive number if the second should, and 0 if they are equal. The spaceship operator <=> returns exactly that.

php · try it yourself
<?php
$products = [
    ['name' => 'Lamp',  'price' => 30, 'stock' => 4],
    ['name' => 'Desk',  'price' => 120, 'stock' => 2],
    ['name' => 'Chair', 'price' => 30, 'stock' => 9],
];

// cheapest first; for equal prices, more stock first
usort($products, function (array $a, array $b): int {
    return [$a['price'], $b['stock']] <=> [$b['price'], $a['stock']];
});

foreach ($products as $p) {
    echo "{$p['name']}: {$p['price']} ({$p['stock']} in stock)" . PHP_EOL;
}

// shorter with an arrow function: alphabetical by name
usort($products, fn($a, $b) => strcmp($a['name'], $b['name']));
echo implode(', ', array_column($products, 'name')) . PHP_EOL;
Chair: 30 (9 in stock)
Lamp: 30 (4 in stock)
Desk: 120 (2 in stock)
Chair, Desk, Lamp

Comparing two small arrays with <=> compares them element by element — a neat trick for multi-field sorts. Swapping $a and $b for one field reverses that field's direction.

Natural order

Humans expect img2 before img10, but a plain string sort puts img10 first because '1' < '2'. natsort() (and natcasesort()) compare the embedded numbers as numbers, keeping the keys.

php · try it yourself
<?php
$files = ['img12.png', 'img10.png', 'img2.png', 'img1.png'];

$plain = $files;
sort($plain);
echo implode(' ', $plain) . PHP_EOL;

natsort($files);
echo implode(' ', $files) . PHP_EOL;
img1.png img10.png img12.png img2.png
img1.png img2.png img10.png img12.png

Tip: Since PHP 8.0 all sorts are stable: items that compare as equal keep their original relative order. That makes "sort by B, then sort by A" a reliable way to sort by A then B.

Test yourself

Which function sorts an associative array by value AND keeps the keys?

  1. sort()
  2. ksort()
  3. asort()
  4. rsort()

What does $x = sort($list); store in $x?

  1. The sorted array
  2. true
  3. The number of items
  4. null

What does 5 <=> 9 evaluate to?

  1. -1
  2. 0
  3. 1
  4. false