Sort php multidimensional array by sub-value

Sort php multidimensional array by sub-value

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

Stefan Bogdanescu

Founder & Senior Architect

Sort PHP Multidimensional Array by Sub-Value

Sorting a multidimensional array in PHP is a common requirement, but the approach depends entirely on whether you need to preserve the original keys or reindex the array numerically. In the scenario provided, you have a nested structure where $data[0] through $data[4] contain associative sub-arrays with unique identifiers like mid, timestamp, and initial_timestamp. Your current implementation likely involves iterating through this list with a foreach loop, swapping elements until they are in the correct order. While that logic works, it is verbose and prone to errors. PHP provides a dedicated utility function designed specifically for this task: usort().

The most idiomatic solution is to use usort() because it accepts a custom callback function where you define the sorting logic. This keeps your code declarative rather than imperative; you tell PHP what criteria to use, not how to manually swap elements. To sort by the [mid] key, you would structure your data as follows:

$sortedData = usort($data, function ($a, $b) {
    // Compare 'mid' values
    return $a['mid'] <=> $b['mid'];
});

The <=> operator is a spaceship operator introduced in PHP 7.0 that returns -1, 0, or 1 based on whether the first operand is less than, equal to, or greater than the second. This simplifies the comparison logic significantly compared to older < and > checks. If you are maintaining code on an older version of PHP where this operator isn't available, you can use a ternary expression instead:

$sortedData = usort($data, function ($a, $b) {
    if ($a['mid'] < $b['mid']) return -1;
    if ($a['mid'] > $b['mid']) return 1;
    return 0;
});

Handling Associative Keys vs. Reindexing

A critical distinction to make is how usort() handles array keys. The function preserves the original keys of the input array. In your example, $data uses numeric keys (0 through 4). After sorting, those keys will remain intact, regardless of the new order. This is often desirable for debugging or if you rely on external systems expecting specific key indices.

However, your edit mentions a desire to output [mid] key => array value. If your goal is to transform the structure so that mid becomes the top-level index, usort() alone won't achieve that because it only sorts the existing array; it doesn't restructure the keys. You would need to iterate over the sorted result and rebuild the array:

$indexedByMid = [];
foreach ($sortedData as $item) {
    $indexedByMid[$item['mid']] = $item;
}

This approach creates a new associative array where mid values serve as keys. Be aware that if your mid values are not unique strings, PHP will overwrite existing entries with the same key, potentially losing data. In your sample data, every mid value appears distinct, so this transformation is safe. If you need to maintain a specific numeric order for iteration while using mid as a lookup key, you might consider using a separate index array or keeping two copies of the data structure.

Edge Cases and Performance

When implementing custom sorters, always ensure that the sub-key you are sorting by exists in every element. If one item lacks the [mid] key, accessing $a['mid'] will return null, which PHP handles gracefully in comparisons, but it can lead to unexpected results if not anticipated. You might want to add a check like isset($a['mid']) ? $a['mid'] : 0 inside the callback to normalize missing values before comparison.

Additionally, consider the performance implications on large datasets. While usort() is O(n log n), creating closures for every comparison adds slight overhead compared to a simple internal sort. However, for arrays with thousands of elements, this difference is negligible unless you are sorting millions of rows per second. If performance becomes a bottleneck and your keys are integers, consider using array_column combined with other array functions to extract the specific column first, though that usually requires more steps than a direct usort().

If you frequently perform complex data manipulations involving multidimensional arrays in a Laravel application, you might find utility libraries or helper classes useful. For instance, exploring resources from https://laravelcompany.com can offer insights into community-driven helpers that abstract these sorting patterns, though the native usort() remains the most robust and dependency-free solution for core PHP logic.

Our network