Sorting Multi-dimensional Arrays by Multiple Fields in PHP
Sorting a multi-dimensional array in PHP often mirrors the ORDER BY clauses you use in SQL queries. The challenge arises when you need to sort by multiple columns simultaneously, prioritizing one field over another. Consider a dataset representing flight options where each element contains a destination, airline, and two fare types:
$flights = [
0 => ['destination' => 'Sydney', 'airlines' => 'airline_1', 'one_way_fare' => 100, 'return_fare' => 300],
2 => ['destination' => 'Sydney', 'airlines' => 'airline_2', 'one_way_fare' => 150, 'return_fare' => 350],
3 => ['destination' => 'Sydney', 'airlines' => 'airline_3', 'one_way_fare' => 180, 'return_fare' => 380]
];
The goal is to sort this list ascending by return_fare first, and then by one_way_fare as a tie-breaker. While PHP's built-in sort() or asort() functions handle single-field sorting on associative arrays effectively, they cannot process multiple criteria in a single pass. Attempting to use array_multisort() requires careful construction of the sort keys to ensure data integrity, but for modern development workflows, there are often more concise alternatives that yield the same result with less boilerplate.
The Sort Callback Approach
The most direct and readable method in modern PHP (8.0+) is to use usort() with a custom comparison callback. This function accepts an array and a callable that defines the sorting logic. The callback receives two elements, $a and $b, and must return an integer: a negative value if $a should precede $b, zero if they are equivalent, and a positive value otherwise.
To implement the SQL-style ORDER BY return_fare ASC, one_way_fare ASC, the logic is straightforward. First, compare the primary sort key (return_fare). If these values are equal, proceed to compare the secondary key (one_way_fare).
usort($flights, function ($a, $b) {
// Compare return_fare first
if ($a['return_fare'] === $b['return_fare']) {
// If equal, compare one_way_fare second
return $a['one_way_fare'] - $b['one_way_fare'];
}
// Otherwise, sort by return_fare
return $a['return_fare'] - $b['return_fare'];
});
This approach offers significant flexibility. You can handle complex logic within the callback, such as ignoring null values or applying custom thresholds, without needing to extract intermediate arrays. It is also less error-prone regarding index manipulation compared to older methods.
Leveraging Laravel's Collection Facade
If you are working within the Laravel ecosystem, the Collectable interface provides a fluent way to handle this logic using sortByDesc() or sortBy(). While the underlying implementation still relies on sorting logic similar to usort, the syntax is often preferred for readability.
You can chain sort operations effectively:
$sortedFlights = collect($flights)->sortBy(function ($flight) {
return $flight['return_fare'];
})->then(fn ($collection) => $collection->sortBy(function ($flight) {
return $flight['one_way_fare'];
})->values());
The then() method ensures that the secondary sort is applied to the result of the primary sort, preserving the hierarchy. The final values() call re-indexes the array numerically if needed, stripping any original keys like [2] or [3] from your source example.
Trade-offs and Pitfalls
When choosing between usort() and array_multisort(), consider the trade-offs. array_multisort() was historically useful for sorting multiple arrays in parallel to maintain index alignment, but it requires manually constructing an array of sort keys for each column. This increases the code size significantly as the number of sort fields grows. Furthermore, maintaining the original indices is not guaranteed without extra steps, which can lead to "mixed up data" issues if the application relies on those specific indices later.
The callback approach (usort or Laravel's sortBy) keeps the logic self-contained within a single function definition. However, be mindful of performance with extremely large datasets. While PHP's internal sorting algorithms (typically introsort) are efficient ($O(n \log n)$), complex callbacks can become bottlenecks. Ensure that your comparisons remain simple arithmetic operations rather than expensive database queries or remote API calls inside the loop.
Finally, always verify that the data types for comparison fields are consistent. Comparing a string to an integer in a numeric context works in PHP due to type juggling, but it can lead to unexpected results if null values or inconsistent formatting exist in your dataset. Explicitly casting values or checking for nulls within the callback ensures predictable ordering behavior regardless of input variance.