PHP example

How to sort a multidimensional array in PHP

9 min read Updated Dec 2026 Runs in an isolated runtime
Quick answer

Use usort with the spaceship operator: usort($rows, fn($a, $b) => $a['age'] <=> $b['age']);. Swap $a and $b on the right for descending order, compare arrays like [$a['city'], $a['age']] <=> [$b['city'], $b['age']] to sort by several columns, and use uasort instead when the outer keys must survive. Objects work the same way with $a->price <=> $b->price.

PHP's plain sort and asort don't know which column of a row you mean, so sorting a list of records (rows from a database, decoded JSON, a list of objects) comes down to a comparison callback. usort calls it with two elements, and the callback returns a negative number, zero or a positive number; <=> (PHP 7.0) produces exactly that in one expression. The sections below cover one column in both directions, several columns, keeping keys, the callback-free array_multisort, objects and string ordering, and what stable sorting guarantees, then a table to pick from. Each example runs on this page: hit Run, then edit the code and run it again.

1usort with the spaceship operatorRecommended

usort($array, $callback) sorts the array in place. The callback gets two elements, $a and $b, and must return an int: below zero when $a comes first, zero when they tie, above zero when $b comes first. $a['age'] <=> $b['age'] returns -1, 0 or 1, which gives ascending order; swap the two sides for descending. The same works for a list of plain rows (a CSV line, a 2D array) using a column index such as $a[1]. The arrow function fn needs PHP 7.4; on older versions write function ($a, $b) { return ...; }.

usort.php
<?php

$people = [
    ['name' => 'Maya', 'age' => 31],
    ['name' => 'Ben', 'age' => 25],
    ['name' => 'Ana', 'age' => 42],
    ['name' => 'Tom', 'age' => 19],
];

// Ascending by age: $a on the left, $b on the right
usort($people, fn(array $a, array $b): int => $a['age'] <=> $b['age']);
foreach ($people as $p) {
    echo $p['name'], ' ', $p['age'], "\n";
}

// Descending: swap the operands
usort($people, fn(array $a, array $b): int => $b['age'] <=> $a['age']);
echo implode(', ', array_column($people, 'name')), "\n";

// Strings compare with <=> too
usort($people, fn(array $a, array $b): int => $a['name'] <=> $b['name']);
echo implode(', ', array_column($people, 'name')), "\n";

// A 2D array without keys: sort by the column index
$rows = [['pear', 3], ['fig', 12], ['apple', 7]];
usort($rows, fn(array $a, array $b): int => $a[1] <=> $b[1]);
echo json_encode($rows), "\n";

// usort returns true, not the sorted array
var_dump(usort($rows, fn(array $a, array $b): int => $a[0] <=> $b[0]));
echo json_encode($rows), "\n";

Output

The ascending pass prints Tom 19 up to Ana 42, the swapped version gives Ana, Maya, Ben, Tom, and sorting by name gives Ana, Ben, Maya, Tom. The keyless rows sort by their second column to [["pear",3],["apple",7],["fig",12]]. The last two lines show the classic mistake: usort prints bool(true) because it sorts the variable you pass and returns true, so $sorted = usort($rows, ...) leaves you holding a boolean. To keep the original, copy it first ($sorted = $rows; copies an array) and sort the copy.

2Sorting by several columns

To sort by city and then by age within each city, compare two arrays: <=> on arrays of the same length compares them element by element and stops at the first difference, so the first element is the main key and the next ones break ties. To reverse just one of the keys, swap $a and $b for that position only. The other common form chains comparisons with ?:, which returns the left side unless it is 0; it reads well when one key needs its own function, such as strcasecmp.

several_columns.php
<?php

$people = [
    ['name' => 'Maya', 'city' => 'Lisbon', 'age' => 31],
    ['name' => 'Ben', 'city' => 'Austin', 'age' => 25],
    ['name' => 'Ana', 'city' => 'Austin', 'age' => 42],
    ['name' => 'Tom', 'city' => 'Lisbon', 'age' => 19],
    ['name' => 'Iris', 'city' => 'Austin', 'age' => 31],
];

function show(array $rows): void
{
    foreach ($rows as $r) {
        printf("%-6s %-4s %d\n", $r['city'], $r['name'], $r['age']);
    }
    echo "--\n";
}

// City A-Z, then age low to high
usort($people, fn(array $a, array $b): int =>
    [$a['city'], $a['age']] <=> [$b['city'], $b['age']]);
show($people);

// City A-Z, then age high to low: swap $a and $b for age only
usort($people, fn(array $a, array $b): int =>
    [$a['city'], $b['age']] <=> [$b['city'], $a['age']]);
show($people);

// The same order with ?: (the first non-zero result wins)
usort($people, fn(array $a, array $b): int =>
    strcasecmp($a['city'], $b['city']) ?: $b['age'] <=> $a['age']);
echo implode(', ', array_column($people, 'name')), "\n";

Output

The first block groups Austin before Lisbon and orders each city by age: Ben 25, Iris 31, Ana 42. Swapping $a and $b in the age slot only flips the age order inside each city (Ana 42 first) while the cities stay A to Z. The ?: version prints the same order, Ana, Iris, Ben, Maya, Tom, with a case-insensitive city compare. <=> binds tighter than ?:, so no parentheses are needed. Keep both arrays the same length: arrays with a different number of elements are compared by count first.

3Keeping the keys with uasort

usort throws the keys away and renumbers the result from 0. That is fine for a list, but when the outer array is keyed by an id or a SKU, the keys are data. uasort takes the same callback and keeps every key with its row. Its siblings: uksort sorts by the keys with a callback, and for a flat key => value array you need no callback at all: asort and arsort sort by value and keep keys, ksort and krsort sort by key.

uasort.php
<?php

$products = [
    'p-101' => ['name' => 'Desk', 'price' => 250],
    'p-102' => ['name' => 'Lamp', 'price' => 40],
    'p-103' => ['name' => 'Chair', 'price' => 120],
];

// usort renumbers: the ids are gone
$list = $products;
usort($list, fn(array $a, array $b): int => $a['price'] <=> $b['price']);
echo implode(', ', array_keys($list)), "\n";

// uasort keeps each key with its row
uasort($products, fn(array $a, array $b): int => $a['price'] <=> $b['price']);
foreach ($products as $id => $p) {
    echo "{$id} {$p['name']} {$p['price']}\n";
}

// uksort sorts by key with a callback (here: descending)
uksort($products, fn(string $a, string $b): int => $b <=> $a);
echo implode(', ', array_keys($products)), "\n";

// A flat key => value array needs no callback
$scores = ['ana' => 82, 'ben' => 95, 'tom' => 78];
arsort($scores);
print_r($scores);

Output

After usort the keys are 0, 1, 2. uasort gives the same price order with the ids intact: p-102 Lamp 40, p-103 Chair 120, p-101 Desk 250. uksort with $b <=> $a lists the keys as p-103, p-102, p-101, and arsort puts [ben] => 95 first with every name still attached to its score. If you later want a plain list, array_values renumbers the result.

4array_multisort with array_column

array_multisort sorts several arrays together: it orders the first one and moves the elements of the others to the same positions. Pull a column out with array_column, pass it first with a direction flag, and pass your data last; the data array is reordered in place. Several columns are just more column, flag pairs. There is no callback, so it is short, but it has two habits to know about: it renumbers integer keys (string keys are kept), and on a tie in every column you gave it, it compares the rows themselves instead of keeping their original order.

multisort.php
<?php

$people = [
    ['name' => 'Tom', 'city' => 'Lisbon', 'age' => 25],
    ['name' => 'Maya', 'city' => 'Lisbon', 'age' => 31],
    ['name' => 'Ben', 'city' => 'Austin', 'age' => 25],
    ['name' => 'Ana', 'city' => 'Austin', 'age' => 42],
];

// One column, descending; $people is reordered in place.
// Tom and Ben tie on 25, so the rows themselves are compared
array_multisort(array_column($people, 'age'), SORT_DESC, $people);
echo implode(', ', array_column($people, 'name')), "\n";

// Two columns: city A-Z, then age high to low
array_multisort(
    array_column($people, 'city'), SORT_ASC,
    array_column($people, 'age'), SORT_DESC,
    $people,
);
echo implode(', ', array_column($people, 'name')), "\n";

// String keys survive, integer keys are renumbered
$byKey = [
    'x' => ['n' => 3],
    7 => ['n' => 2],
    'y' => ['n' => 1],
    9 => ['n' => 0],
];
array_multisort(array_column($byKey, 'n'), SORT_ASC, $byKey);
echo json_encode(array_keys($byKey)), "\n";

Output

The first line is Ana, Maya, Ben, Tom: Tom was listed before Ben and both are 25, yet Ben comes first, because on a tie array_multisort compares the rows, and these rows start with name. usort would keep Tom first (see section 6). The two-column call gives Ana, Ben, Maya, Tom. The keys come back as [0,"y",1,"x"]: x and y survive, 7 and 9 were renumbered. Every row must have the column, or array_column returns a shorter array and the call throws ValueError: Array sizes are inconsistent. For text columns, pass SORT_NATURAL | SORT_FLAG_CASE after the direction.

5Objects by a property, and string order

An array of objects sorts with the same usort call; read the property with -> instead of a key. Text is where the comparison choice matters. <=> and strcmp compare bytes, so every uppercase letter sorts before every lowercase one and "Item 10" comes before "Item 9". strcasecmp ignores case, and strnatcasecmp also reads runs of digits as numbers, which is the order people expect for names and file names.

objects.php
<?php

final class Product
{
    public function __construct(
        public readonly string $name,
        public readonly float $price,
    ) {}
}

$items = [
    new Product('Item 10', 7.0),
    new Product('item 9', 4.25),
    new Product('Item 1', 12.0),
    new Product('adapter', 4.5),
];

function names(array $items): string
{
    return implode(' | ', array_map(fn(Product $p) => $p->name, $items));
}

// By a numeric property
usort($items, fn(Product $a, Product $b): int => $a->price <=> $b->price);
echo names($items), "\n";

// Byte order: uppercase first, "10" before "9"
usort($items, fn(Product $a, Product $b): int => strcmp($a->name, $b->name));
echo names($items), "\n";

// Natural order, ignoring case
usort($items, fn(Product $a, Product $b): int =>
    strnatcasecmp($a->name, $b->name));
echo names($items), "\n";

// strcmp gives the sign, not always -1 or 1
var_dump(strcmp('10', '9'), '10' <=> '9');

Output

By price the order is item 9 | adapter | Item 10 | Item 1. strcmp gives Item 1 | Item 10 | adapter | item 9: capital I sorts before lowercase a, and "Item 10" lands before "item 9". strnatcasecmp gives the human order, adapter | Item 1 | item 9 | Item 10. The last two lines are a gotcha: strcmp('10', '9') returns -8, so test its sign with < 0, never === -1, and '10' <=> '9' returns 1 because <=> compares two numeric strings as numbers. Sorting by language rules (accents, locale order) needs Collator from the intl extension, which is not loaded here.

6Equal elements keep their order (PHP 8.0+)

Since PHP 8.0 every sort function is stable: when the callback returns 0, the two elements stay in the order they had before the sort. On PHP 7 that was not guaranteed, and ties could come out in any order. Stability gives you a second way to sort by several columns: sort by the minor key first, then by the major key, and the minor order survives inside each group.

stable.php
<?php

$orders = [
    ['id' => 1, 'status' => 'shipped', 'total' => 30],
    ['id' => 2, 'status' => 'pending', 'total' => 55],
    ['id' => 3, 'status' => 'shipped', 'total' => 12],
    ['id' => 4, 'status' => 'pending', 'total' => 20],
    ['id' => 5, 'status' => 'shipped', 'total' => 55],
];

function ids(array $rows): string
{
    return implode(' ', array_column($rows, 'id'));
}

// Sort by status only: ties keep their id order
$byStatus = $orders;
usort($byStatus, fn(array $a, array $b): int => $a['status'] <=> $b['status']);
echo ids($byStatus), "\n";

// Two passes: minor key first (total), then major key (status)
$twoPass = $orders;
usort($twoPass, fn(array $a, array $b): int => $a['total'] <=> $b['total']);
usort($twoPass, fn(array $a, array $b): int => $a['status'] <=> $b['status']);
echo ids($twoPass), "\n";

// Same result as one pass with both keys
$onePass = $orders;
usort($onePass, fn(array $a, array $b): int =>
    [$a['status'], $a['total']] <=> [$b['status'], $b['total']]);
echo ids($onePass), "\n";

Output

Sorting by status alone prints 2 4 1 3 5: the pending orders 2 and 4, then the shipped orders 1, 3 and 5, each group still in id order. Sorting by total and then by status prints 4 2 3 1 5, the same as the one-pass comparison on [status, total]: inside each status group the orders run from the smallest total up. On PHP 7, write the full comparison instead of relying on the two-pass trick.

7Which should you use?

MethodKeysBest for
usort + <=>RenumberedMost cases: lists of arrays or objects
[$a[x], $a[y]] <=> [...]RenumberedSeveral columns, any mix of directions
uasortKeptRows keyed by id, SKU or name
array_multisortStrings kept, ints renumberedShort column sorts without a callback
strnatcasecmpn/aNames and file names with numbers
asort / arsort / ksortKeptFlat key => value arrays

Frequently asked questions

Why does usort return true instead of the sorted array?

usort, like every PHP sort function, sorts the array you pass by reference and returns true. Call it on its own line and use the same variable afterwards: usort($rows, $cmp); print_r($rows);. If you need the original too, copy it first with $sorted = $rows; and sort $sorted.

How do I sort a multidimensional array by a column in descending order?

Swap the operands of the spaceship operator: usort($rows, fn($a, $b) => $b['age'] <=> $a['age']);. With array_multisort, pass SORT_DESC after the column: array_multisort(array_column($rows, 'age'), SORT_DESC, $rows);. Avoid sorting ascending and then calling array_reverse, which also reverses the order of equal elements.

What does "Returning bool from comparison function is deprecated" mean?

Your callback returns $a > $b instead of a number. PHP 8 prints Deprecated: usort(): Returning bool from comparison function is deprecated, return an integer less than, equal to, or greater than zero. A boolean cannot say "equal", so PHP has to call the callback again to tell ties apart. Return $a <=> $b instead.

Why does returning $a['price'] - $b['price'] not sort my array?

The callback result is converted to an int, so a float difference such as 0.3 becomes 0, which means "equal". With prices 1.5, 1.2, 1.9 and 1.1 that callback left them as 1.5 1.2 1.9 1.1. Subtraction is also wrong for strings. Use $a['price'] <=> $b['price'], which returns -1, 0 or 1 for any type.

How do I sort an array by a date column?

Dates stored as Y-m-d or Y-m-d H:i:s strings sort correctly with <=>, because their text order is their time order. Other formats do not: 03/01/2026 sorts before 12/25/2025 as text. Convert inside the callback, strtotime($a['d']) <=> strtotime($b['d']), or compare DateTimeImmutable objects, which also work with <=>.

What is the difference between sort, asort, ksort, usort, uasort and uksort?

sort and rsort sort by value and renumber the keys; asort and arsort sort by value and keep the keys; ksort and krsort sort by key. The versions starting with u take your comparison callback: usort renumbers, uasort keeps keys, uksort compares keys. For arrays of arrays or objects you almost always want usort or uasort.

Is sorting stable in PHP?

Yes, since PHP 8.0 all sort functions are stable: elements that compare equal keep their original order. On PHP 7 and earlier the order of ties was not defined. array_multisort is the odd one out in practice: on a tie in every column you give it, it compares the rows themselves rather than keeping their input order.

Run it yourself

Open any of these in the full PHP editor to tweak, run and share.

PHP playground