Sort rows of a 2d array by a column

Sort rows of a 2d array by a column

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

Stefan Bogdanescu

Founder & Senior Architect

Sorting Two-Dimensional Arrays by Specific Columns

You have a collection of associative arrays representing configuration options, and you need to order them strictly by the optionNumber index. In this specific dataset, that means transitioning from an unsorted list where optionNumber values are 3, 2, and 1 into a sequence where they read 1, 2, and 3. While PHP offers multiple ways to handle this, the most pragmatic approach depends on whether you need a stable sort or if you are working within the Laravel ecosystem.

The Built-in uasort Approach

If you are dealing with a standalone array outside of a framework, the standard library function uasort() is often the first line of defense. Unlike usort(), which reindexes the array using numeric keys and breaks the associative nature of your data, uasort() preserves the original keys. This distinction matters if your code relies on those specific identifiers later in the execution flow.

To apply a custom sort order based on optionNumber, you define a comparison function that extracts the value at that index from two different items being compared. The logic is straightforward: subtract the first item's value from the second. If the result is negative, the first item comes first; if positive, the second comes first.

$data = [
    ['configuration_id' => 10, 'optionNumber' => 3],
    ['configuration_id' => 9,  'optionNumber' => 2],
    ['configuration_id' => 8,  'optionNumber' => 1],
];

uasort($data, function ($a, $b) {
    return $a['optionNumber'] <=> $b['optionNumber'];
});

The spaceship operator (<=>) handles the comparison cleanly, returning -1, 0, or 1. This ensures that if two items share the same optionNumber, their relative order remains unchanged, which is a property known as stability. If you were using usort() instead, and your original array had non-sequential numeric keys (e.g., strings or sparse indices), you would lose that data structure entirely upon sorting.

Leveraging Laravel Collections

However, if your application stack includes the Laravel framework, you are likely already using Eloquent collections or manually constructing a Collection instance. In this context, calling sort() on a collection is significantly more expressive and safer than reaching for raw PHP functions. The sort() method in Laravel accepts an optional closure that defines the sorting logic, effectively encapsulating the comparison rule within the collection itself.

use Illuminate\Support\Collection;

$collection = collect($data);

$sortedData = $collection->sortBy('optionNumber')->toArray();

This syntax is not only cleaner but also integrates seamlessly with the rest of Laravel's query building and data manipulation methods. If your optionNumber values represent a specific business logic where you might need to handle missing keys gracefully, you can chain this with filtering or map operations before or after sorting. For instance, if certain rows have a null optionNumber, sortBy will naturally place them at the end, whereas a custom comparison function might throw an error depending on how strictly you define the fallback value.

Performance and Trade-offs

It is important to recognize that sorting algorithms generally operate in O(n log n) time complexity. For small datasets like the example provided here containing just three rows, performance is irrelevant. However, as the dataset grows into thousands of rows—typical for large configuration tables or audit logs—the overhead of a custom sort becomes noticeable.

When choosing between uasort and Laravel's sortBy, consider the source of your data. If you are sorting an array resulting from a raw SQL query using pluck() or similar eager loading, wrapping it in a collection adds a layer of abstraction but keeps the codebase consistent with Laravel conventions. Conversely, if you are optimizing for maximum speed in a non-framework context and the dataset is massive, sticking to native PHP functions avoids the overhead of creating a collection object solely for the sort operation.

Finally, always verify that the column you are sorting by exists in every row. If your data model allows for missing optionNumber fields, ensure your comparison logic handles nulls explicitly to prevent unexpected behavior during execution.

Our network