Sort multidimensional array by multiple columns

Sort multidimensional array by multiple columns

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Sort multidimensional array by multiple columns

Sorting a multidimensional array in PHP requires more than just passing keys to a built-in function. When you need complex, multi-level sorting logic—like ordering events by state first, then event type, and finally date—the standard uasort() or usort() functions become your primary tools. The key is constructing a custom comparison callback that handles the hierarchy of your sort criteria correctly.

In your specific scenario, you have an array of events where each item contains state, event_type, and date_start. You want to prioritize sorting by state (ascending), then break ties with event_type (ascending), and finally resolve remaining duplicates using date_start (ascending). The logic must check these conditions sequentially.

To implement this, you define a comparison function that returns an integer: negative if the first item should come before the second, positive if it should come after, and zero if they are equal at that level.

usort($events, function ($a, $b) {
    // 1. Sort by state first
    $stateCompare = strcmp($a['state'], $b['state']);
    if ($stateCompare !== 0) {
        return $stateCompare;
    }

    // 2. If states are equal, sort by event_type
    $typeCompare = strcmp($a['event_type'], $b['event_type']);
    if ($typeCompare !== 0) {
        return $typeCompare;
    }

    // 3. If types are equal, sort by date_start
    // Since dates are strings in YYYY-MM-DD format, string comparison works correctly for sorting.
    return strcmp($a['date_start'], $b['date_start']);
});

The usort() function will rearrange the $events array based on this logic. Notice that we use strcmp() for every step. This is crucial because it guarantees a consistent ASCII-based sort order for strings like 'california' versus 'new-york'. If your data contained dates stored as timestamps (integers), you would use subtraction or strtotime() comparisons instead, but string comparison works perfectly for ISO 8601 formatted dates like '2010-07-30'.

Preserving Original Keys

One common pitfall when writing custom sorters is choosing the wrong function. If you use sort(), asort(), or arsort(), PHP will reset the numeric keys of your array to 0, 1, 2, etc. Since your example data includes an ID field that acts as a unique identifier, preserving the original key associations is often desirable, especially if you plan to use these IDs later in your application.

For this reason, uasort() is the correct choice here. It maintains the original keys of the array while reordering the elements based on the comparison function. If you were using an associative array where the keys are strings (like 'user_id' instead of numeric indices), uksort() would be appropriate, but for standard list data, uasort() strikes the right balance between stability and performance.

Performance Considerations

While usort() is robust, it has a time complexity of O(n log n). For small datasets like the four items in your example, performance is negligible. However, if you are dealing with thousands of records, the overhead of a custom PHP callback can become significant compared to native database sorting or using Laravel's query builder.

If you find yourself querying a database for this specific ordering, it is almost always more efficient to push the sorting logic into your SQL query. Databases are optimized for multi-column sorting (using ORDER BY clauses) and can execute these operations in memory without transferring the entire dataset back to PHP just to sort it. You should only use PHP-side sorting when the data is already fetched or when the dataset size remains small enough that the CPU cost of the callback outweighs the benefit of keeping logic on the server side.

Handling Null Values

A potential edge case arises if your data might contain null values for any of the sort keys. The strcmp() function expects two strings as arguments. Passing a string and a null value will trigger a warning in PHP 8.x or result in unexpected behavior depending on the version. To make your sorter resilient, you should normalize the data within the callback before comparing:

$stateA = $a['state'] ?? '';
$stateB = $b['state'] ?? '';
$compare = strcmp($stateA, $stateB);
if ($compare !== 0) return $compare;

$typeA = $a['event_type'] ?? '';
$typeB = $b['event_type'] ?? '';
$compare = strcmp($typeA, $typeB);
if ($compare !== 0) return $compare;

$dateA = $a['date_start'] ?? '9999-12-31'; // Default to end of time
$dateB = $b['date_start'] ?? '9999-12-31';
return strcmp($dateA, $dateB);

By providing defaults, you ensure the sort order remains stable even if your data is incomplete. This defensive programming practice prevents warnings from cluttering your logs and ensures predictable results regardless of data quality.

Our network