Sort a 2D Array by a Column Value
Sorting a multidimensional array in PHP requires moving beyond simple built-in functions like sort() or asort(), which operate only on one-dimensional structures. When your data is nested, as in the example where each element contains an order key alongside other metadata like hashtag and title, you need to tell the sorting algorithm exactly which column determines the sequence.
The standard approach relies on usort(). This function accepts a custom comparison callback that defines how two elements should be ordered relative to one another. To sort by the order key, you pass a closure to usort() that extracts the specific value from each array being compared and returns the result of subtracting them.
$data = [
0 => ['hashtag' => 'a7...', 'title' => 'Flower', 'order' => 3],
1 => ['hashtag' => 'b2...', 'title' => 'Free', 'order' => 2],
2 => ['hashtag' => 'e7...', 'title' => 'Ready', 'order' => 1],
];
usort($data, function ($a, $b) {
return $a['order'] <=> $b['order'];
});
The crucial part here is the spaceship operator (<=>). Introduced in PHP 7.0, this operator returns -1 if the left operand is smaller, 1 if it is larger, and 0 if they are equal. This return value directly maps to what usort() expects: negative for ascending order, positive for descending, and zero to maintain stability. If you were using PHP 6 or earlier, you would have to manually calculate the difference and cast it to an integer, but modern environments make this syntax much cleaner.
While usort() is robust, it modifies the original array by reference. If your application logic requires preserving the unsorted dataset for subsequent operations, pass a copy of the array to the function instead. Using array_values() after sorting can also reset the keys to a sequential numeric range (0, 1, 2...) if you prefer that over preserving the original indices.
Another viable option is uasort(), which stands for "unordered associative sort." Unlike usort(), this function preserves the original keys of the array during the sorting process. However, there is a significant performance trade-off. The spaceship operator (<=>) was optimized in PHP 7 to handle comparisons at the opcode level with minimal overhead. In contrast, uasort() calls your callback function explicitly for every comparison step, which can introduce noticeable overhead in tight loops or large datasets. If you do not require key preservation, usort() remains the preferred choice for raw performance.
If you are working within a Laravel application, you might consider leveraging the collection system. Converting an array to a Collection allows you to use method chaining, which can make the code more readable if you need to filter or transform data in subsequent steps. The underlying logic remains the same, but the syntax shifts to sortBy():
$collection = collect($data)->sortBy('order');
This abstraction is convenient and reduces boilerplate, though it adds a small memory overhead by creating a collection object. For simple sorting tasks where performance is critical and no further collection methods are needed, sticking to the raw PHP array functions avoids that unnecessary allocation.
Finally, be mindful of data types. The order key in your example contains integers, which makes numeric comparison straightforward. If these values were strings, such as "1", "10", and "2", a simple subtraction would result in lexicographical sorting (where "10" comes before "2"). In those cases, you would need to cast the values to integers inside the callback or use strnatcmp() if handling filenames. Always verify the data type of your sort column to ensure the comparison logic matches your intended ordering behavior.