← All posts

PHP: how to sort an array (simple, associative or multidimensional) with sort, usort and array_multisort

Which PHP sort function keeps keys, how to sort an array of arrays by one or more columns, how to handle dates, accents and empty values, and the traps that produce the wrong order without any error.

PHP: how to sort an array (simple, associative or multidimensional) with sort, usort and array_multisort

Key points

  • PHP’s sort functions work in place; those starting with “a” or “k” keep your keys.
  • For an array of arrays, usort() with the <=> operator covers nearly every case, including multi-column sorting.
  • Dates stored as text, accents, decimals and comparators that return booleans all produce wrong orders with no error message.

Sorting an array is one of those tasks everyone thinks they’ve mastered, right up until a client reports that “the cheapest products aren’t first” or that “Écully shows up after Zurich”. PHP has a dozen sort functions with similar names, and most of the sorting bugs we fix come from picking the wrong one, or from a comparison function that looks right but isn’t. Here’s how to choose the right function, sort arrays of arrays by one or more columns, handle real-world data (dates, accents, empty values) and avoid the silent traps.

sort, asort, ksort: which one keeps the keys?

Every PHP sort function works in place: it modifies the array you pass in and returns true. The naming rule fits in two letters: a name starting with a (associative) keeps key-value pairs together, a name starting with k sorts by key, and an r reverses the order.

<?php
$prices = ['chair' => 49, 'table' => 189, 'lamp' => 35];

sort($prices);    // [35, 49, 189]                         keys lost
asort($prices);   // ['lamp' => 35, 'chair' => 49, ...]  keys kept, sorted by value
ksort($prices);   // ['chair' => 49, 'lamp' => 35, ...]  sorted by key
arsort($prices);  // like asort, but descending (krsort for keys)

// File names: "human" order rather than character-by-character order
$files = ['img12.png', 'img10.png', 'IMG2.png'];
sort($files, SORT_NATURAL | SORT_FLAG_CASE);
// ['IMG2.png', 'img10.png', 'img12.png']

Calling sort() on an associative array is the most common mistake: keys are replaced with 0, 1, 2… If the array was indexed by product ID, those IDs are gone, and any code relying on them afterwards finds nothing.

The second parameter (the flags) is worth setting explicitly whenever the data is mixed. SORT_STRING forces a text comparison, SORT_NUMERIC a numeric one, and SORT_NATURAL natural order, where “img2” comes before “img10”. Without a flag, PHP compares by value type, and an array mixing '10', '9' and 'abc' can come out in a surprising order.

Sorting an array of arrays with usort and the <=> operator

Query results, product lists, CSV rows: most of the time you’re sorting arrays of arrays (or objects) by a field. That’s the job of usort(), which takes a comparison function. The function must return a negative, zero or positive integer, which is exactly what the spaceship operator <=> does:

<?php
$products = [
    ['name' => 'Lamp',  'category' => 'Decor',    'price' => 35.0],
    ['name' => 'Table',  'category' => 'Furniture', 'price' => 189.0],
    ['name' => 'Chair', 'category' => 'Furniture', 'price' => 49.9],
];

// Price, ascending
usort($products, fn(array $a, array $b): int => $a['price'] <=> $b['price']);

// Price, descending: just swap $a and $b
usort($products, fn(array $a, array $b): int => $b['price'] <=> $a['price']);

// Category A→Z, then price descending within each category
usort($products, fn(array $a, array $b): int =>
    [$a['category'], $b['price']] <=> [$b['category'], $a['price']]
);

The last example is the one people forget. Comparing two arrays with <=> compares their elements one by one, in order, so you get a multi-column sort in a single line with no cascade of if statements. To reverse just one column, swap $a and $b for that column only, as with the price here.

usort() reindexes the array. If the keys matter, use uasort(), which works the same way but keeps them, or uksort() to compare the keys themselves. With objects the syntax is identical: $a->price <=> $b->price.

Since PHP 8.0, sorting is stable: equal elements keep their original order, which PHP 7 didn’t guarantee.

Real-world cases: dates, accents, empty values, WordPress

Tutorials sort tidy numbers. In production you sort dates stored as text, city names with accents and fields that are sometimes empty. Here’s what we use on our projects:

<?php
// 1. Dates stored as dd/mm/yyyy: convert them before comparing
usort($orders, fn($a, $b) =>
    DateTimeImmutable::createFromFormat('d/m/Y', $a['date'])
    <=> DateTimeImmutable::createFromFormat('d/m/Y', $b['date'])
);

// 2. Accents: "Écully" should come before "Lyon", not after "Zurich"
$collator = new Collator('fr_FR');          // intl extension
usort($cities, fn($a, $b) => $collator->compare($a, $b));

// 3. Empty values last
usort($tasks, fn($a, $b) =>
    [$a['due'] === null, $a['due']] <=> [$b['due'] === null, $b['due']]
);

// 4. WordPress: sort a list of objects or arrays by a field
$pages = wp_list_sort($pages, 'menu_order', 'ASC');

For dates, a string in YYYY-MM-DD format (or Y-m-d H:i:s) can be compared directly as text, because alphabetical and chronological order match. That’s not true of dd/mm/yyyy (or the US mm/dd/yyyy): “02/01/2026” sorts before “15/12/2025”. On a long list, build the date objects once before sorting rather than on every comparison.

For accents, the default comparison is byte by byte, so every accented letter lands after “z”. The Collator class from the intl extension applies the rules of a given locale, and also offers $collator->sort() and asort() for simple arrays. Check that intl is enabled on the production server, not just your machine. Names from many languages (French, German, Spanish, Scandinavian) all need this.

The empty-values trick relies on array comparison: false sorts before true, so items with no due date end up at the bottom. In WordPress, wp_list_sort() saves you writing a comparator for simple cases, and even accepts an array of fields and directions.

array_multisort, and when to sort somewhere other than PHP

array_multisort() sorts several arrays at once, using the first as the key. Combined with array_column(), it sorts an array of arrays by column:

<?php
// Sort by price descending, then by name, with array_multisort
$priceCol = array_column($products, 'price');
$nameCol = array_column($products, 'name');

array_multisort($priceCol, SORT_DESC, SORT_NUMERIC,
                $nameCol,  SORT_ASC,  SORT_STRING,
                $products);

The result matches usort() but reads worse: we only reach for it on large datasets.

Above all, if the data comes from a database, sort it in the SQL query with ORDER BY. That’s essential as soon as there’s pagination: sorting page 2 in PHP is not the same as sorting the whole result set. The database also has indexes and collation rules for accents. Sorting in PHP is still the right tool for data from an API, a file or a calculation done after the query.

The traps that give the wrong order without an error

Three mistakes come up again and again in the code reviews we do, including in code written by AI assistants:

<?php
// Trap 1: usort() sorts in place and returns true, not the array
$sorted = usort($products, $cmp);     // $sorted is true!

// Trap 2: returning a boolean (deprecated since PHP 8.0, unreliable result)
usort($products, fn($a, $b) => $a['price'] > $b['price']);

// Trap 3: subtracting decimals
usort($products, fn($a, $b) => $a['price'] - $b['price']); // 0.4 becomes 0: "equal"

// Correct in all three cases
usort($products, fn($a, $b) => $a['price'] <=> $b['price']);

The first trap shows an empty list or causes an error further down, because the variable holds true. The second worked by luck in PHP 7; PHP 8 raises a deprecation notice and the order can be wrong, because a function returning a boolean never distinguishes “less than” from “equal”. The third is the sneakiest: the return value is cast to an integer, so a 0.40 difference becomes 0 and two different prices are treated as equal. It only shows up with close prices, so rarely in testing.

To catch them, a unit test with close values and ties is usually enough, and static analysis (PHPStan or Psalm) flags comparison functions that don’t return an integer.

FAQ

How do I sort an array without changing the original?

Since sort functions work in place, copy first: $copy = $array; usort($copy, $cmp);. PHP arrays are copied on assignment, so the original stays untouched.

How do I sort randomly?

shuffle() randomises an array and reindexes its keys. For a reproducible random order (the same for a given visitor, say), use PHP 8.2’s RandomRandomizer class with a seeded engine.

A wrong sort on a price list or an order history is the kind of detail that makes a customer doubt the whole site. We build and take over PHP and WordPress applications, with code reviews and tests that catch these bugs before your users do.

Share LinkedIn Facebook X WhatsApp
</>

webtestudio

Web agency: custom WordPress sites, premium themes and SaaS software.

Discuss your project →