How to Sort a Multidimensional Array in PHP

Sorting a list of rows by one of their fields is something every PHP developer runs into — users by name, products by price, posts by date. This tutorial shows five ways to sort a multidimensional array in PHP, from usort with the spaceship operator to array_multisort, plus how to sort by several keys at once and keep your original keys intact.

RH Raja HunainAuthor 25 Nov 2026 8 min read 5 views
Table of Contents
Share

Sooner or later every PHP developer faces the same problem: an array of rows — users from a database, products from an API, posts from a JSON file — arrives in the wrong order. You need them sorted by name, by price, or by date, but PHP's plain sort() only knows how to order simple values. Give it an array of arrays and it compares whole rows in ways you did not ask for.

The good news is that PHP has the right tools built in. This tutorial shows five ways to sort a multidimensional array in PHP, starting with the one you will use most often.

The sample data

Every example in this tutorial sorts the same list of products:

$products = [
    ['id' => 3, 'name' => 'Keyboard', 'price' => 49.99, 'stock' => 12],
    ['id' => 1, 'name' => 'Mouse',    'price' => 19.99, 'stock' => 40],
    ['id' => 2, 'name' => 'Monitor',  'price' => 199.99, 'stock' => 7],
    ['id' => 4, 'name' => 'Webcam',   'price' => 49.99, 'stock' => 25],
];

The goal is to order these rows by the price field — cheapest first.

Method 1: usort with the spaceship operator — the standard way

usort() sorts an array using a comparison function you supply. It receives two rows, $a and $b, and must return a negative number when $a comes first, a positive number when $b comes first, and 0 when they are equal. PHP's spaceship operator <=> returns exactly that, so the whole sort fits on one line:

usort($products, fn($a, $b) => $a['price'] <=> $b['price']);

After this call the order is Mouse ($19.99), Keyboard ($49.99), Webcam ($49.99), Monitor ($199.99). Two rows share the price $49.99 — since PHP 8.0 sorting is stable, equal rows keep their previous order, so Keyboard stays before Webcam.

For descending order, swap the two sides:

usort($products, fn($a, $b) => $b['price'] <=> $a['price']);

Sorting strings works the same way. To order the same rows by name alphabetically, compare the name field — and wrap it in strtolower() if the data mixes upper and lower case:

usort($products, fn($a, $b) => strtolower($a['name']) <=> strtolower($b['name']));

This is the method to reach for first: readable, and it works on any PHP version from 7.4 onwards (the arrow function needs 7.4; on older versions use a regular function ($a, $b) { ... }).

One thing to remember: usort() renumbers the array keys from 0. If your rows are keyed by something meaningful — a user id, for example — the keys are lost. Method 4 below fixes that.

Method 2: array_multisort with array_column — no callback needed

If you prefer no comparison function, array_multisort() sorts by one or more columns. Pull the column out with array_column(), then sort the column and the rows together:

array_multisort(array_column($products, 'price'), SORT_ASC, $products);

array_multisort() sorts the first argument and reorders every array that follows it in exactly the same way, so the rows stay matched to their prices. The flags say what kind of sort to apply: SORT_ASC or SORT_DESC for direction, and optionally SORT_NUMERIC or SORT_STRING for the comparison type — SORT_NUMERIC matters when your prices arrive as strings from a database or a CSV file, because a plain string comparison would put '199.99' before '49.99'.

This method fits when the data is a plain list of rows and you need no custom comparison. It is less flexible than usort() — no multi-key rule fits in one call — but for a single key it is the shortest code of all.

Method 3: Sort by more than one key

Real data rarely has a single obvious sort key. In the sample above, Keyboard and Webcam cost the same $49.99. Sorting by price first and then by stock — so the better-stocked item comes first among equals — needs a comparison that checks the keys in order:

usort($products, function ($a, $b) {
    // 1. Price first, cheapest first
    if ($a['price'] !== $b['price']) {
        return $a['price'] <=> $b['price'];
    }
    // 2. Same price? More stock first
    return $b['stock'] <=> $a['stock'];
});

Now Webcam (stock 25) comes before Keyboard (stock 12) at the same price. The pattern scales to any number of keys: compare the first key, return immediately when it decides the order, and only move to the next key when the values are equal.

Method 4: uasort — sort without losing your keys

usort() and array_multisort() both renumber the array, so $products[3] no longer means "the row with id 3". When the keys matter — an array keyed by user id, for instance — use uasort(), which sorts by value but keeps the original keys attached to their rows:

$byId = [
    3 => ['name' => 'Keyboard', 'price' => 49.99],
    1 => ['name' => 'Mouse',    'price' => 19.99],
    2 => ['name' => 'Monitor',  'price' => 199.99],
];

uasort($byId, fn($a, $b) => $a['price'] <=> $b['price']);

foreach ($byId as $id => $row) {
    echo "$id: {$row['name']}\n";
}
// 1: Mouse
// 3: Keyboard
// 2: Monitor

The rows are now in price order, but key 1 still points at Mouse and 3 at Keyboard. uksort() is the matching function for sorting by key, and asort() is the equivalent for a one-dimensional array. Picking the wrong member of this family — sort() when you meant uasort() — is a common PHP bug, because the code runs without an error and the data just comes out wrong.

Method 5: Sorting dates and mixed data

Dates stored as strings in YYYY-MM-DD format sort correctly with a plain string comparison, because the most significant part comes first. So sorting posts by a published_at string needs nothing special:

usort($posts, fn($a, $b) => $a['published_at'] <=> $b['published_at']);

Other date formats do not behave this way. '25/11/2026' compared as a string puts the day first, which is wrong. And strtotime() will not save you here either: for slash-separated dates it assumes the American m/d/Y order, so strtotime('25/11/2026') returns false. The correct tool is DateTime::createFromFormat(), where you state the format yourself:

usort($posts, fn($a, $b) =>
    DateTime::createFromFormat('d/m/Y', $a['published_at'])->getTimestamp()
    <=> DateTime::createFromFormat('d/m/Y', $b['published_at'])->getTimestamp()
);

The same idea applies to any field that needs normalising: trim stray spaces, cast numeric strings with (float), or lowercase text. Keep the callback cheap — it runs roughly n log n times, so prepare an expensive field once before sorting, not inside every comparison.

Common mistakes to avoid

Using sort() on a multidimensional array. sort($products) compares whole rows with PHP's standard comparison, which looks at the first differing element — usually the id — and ignores the field you actually care about. The result looks sorted, but by the wrong thing.

Forgetting that usort() renumbers keys. If anything later in the code reads $products[2] expecting a specific row, the sort has silently broken that assumption. Use uasort() when keys carry meaning.

Comparing with == and returning a boolean. A comparison function must return an integer. return $a['price'] == $b['price']; returns true or false, which PHP casts to 1 or 0 — the sort then treats "less than" and "equal" as the same thing and the order becomes unpredictable. The spaceship operator exists precisely to avoid this.

Missing keys. If some rows lack the field you sort by, $a['price'] throws an "undefined array key" warning in PHP 8. Guard it with the null coalescing operator — $a['price'] ?? 0 sends incomplete rows to the front for an ascending sort.

Which method should you use?

Goal Best method
Sort by one field, simplest code Method 1 — usort() with <=>
Sort by one field, no callback Method 2 — array_multisort() + array_column()
Sort by two or more fields Method 3 — usort() with chained comparisons
Sort but keep the original keys Method 4 — uasort()
Sort dates or values that need normalising Method 5 — convert inside the comparison

Common questions

Is usort() stable in PHP? Yes — since PHP 8.0, elements that compare as equal keep their original relative order. On PHP 7.4 and older the order of equal elements was undefined, so add a tiebreaker key to make the result deterministic.

Can I sort by a nested key? Yes — reach into the nested array in the comparison: fn($a, $b) => $a['author']['name'] <=> $b['author']['name']. Guard the nested key with ?? if some rows might not have it.

What is the difference between usort() and array_multisort()? usort() takes a callback, so it can express any rule — multi-key sorts, case-insensitive comparison, custom ordering. array_multisort() takes columns and flags, so it is shorter for a single key but cannot express a custom rule. Both sort in place and return true, not the sorted array — a detail that trips up developers who write $sorted = usort(...) and then wonder why $sorted is a boolean.

How do I sort an array of objects? The same way, with object syntax in the callback: usort($users, fn($a, $b) => $a->created_at <=> $b->created_at). array_multisort() does not work directly on objects, so usort() is the natural choice there.

Conclusion

Sorting a multidimensional array in PHP comes down to one idea: tell PHP which field decides the order, and let a comparison function do the rest. usort() with the spaceship operator covers almost every case — one key, several keys, numbers, strings and dates — array_multisort() with array_column() is the shorter route for a single key, and uasort() is the answer whenever the original keys must survive the sort.

#PHP #Arrays #Sorting #PHP8 #WebDevelopment

Was this helpful? 0 likes Login to like & bookmark
RH

Written by

Raja Hunain

Full Stack Developer at Raja Dev Solutions — writes about real development work, the errors he faced and exactly how he fixed them, plus practical Laravel, PHP, JavaScript and MySQL tutorials.

More about the author

Comments (0)

No comments yet. Be the first to comment.

Leave a comment

Comments are moderated and appear after approval.

Keep reading

Related Articles