Sorting Multidimensional Arrays by Subarray Values in PHP
When you need to order a multidimensional array based on a specific key within its subarrays, the standard sort() function isn't enough. The built-in sort() operates only on one-dimensional arrays and will destroy your associative keys if used directly on a nested structure. To achieve alphabetical ordering of names in your data structure, you must use uasort() or usort().
Consider an array structured like this:
$data = [
0 => ['name' => 'Bill', 'age' => 15],
1 => ['name' => 'Nina', 'age' => 21],
2 => ['name' => 'Peter', 'age' => 17]
];
The goal is to reorder $data so that the entries appear as Bill, Nina, then Peter. The most robust approach involves using uasort() with a custom comparison function. This function takes two keys from the top-level array and returns an integer to indicate their relative order.
Here is the implementation:
uasort($data, function ($a, $b) {
if ($a['name'] == $b['name']) {
return 0;
}
return ($a['name'] < $b['name']) ? -1 : 1;
});
This code defines a closure that compares the name property of two subarrays. If the names are identical, it returns 0, indicating they are equal in sort order. If $a['name'] comes before $b['name'] alphabetically, it returns -1. Otherwise, it returns 1. After running uasort(), the original array is modified in place, preserving the integer keys while reordering the elements based on the comparison logic.
If you prefer a more concise syntax available in PHP 5.4 and later, you can use arrow functions:
uasort($data, fn ($a, $b) => strcasecmp($a['name'], $b['name']));
Using strcasecmp() is often preferable to manual comparison operators because it handles case-insensitivity automatically. In the original example, "Bill" and "bill" would be treated as equal; without this function, a capital "B" might sort differently than a lowercase "b". This function returns -1 if $a is less than $b, 0 if they are equal, and 1 if $a is greater than $b.
An alternative approach involves usort(), which accepts the array by value rather than by reference. While usort() creates a copy of the array before sorting, this can be useful if you want to preserve the original order while generating a sorted version. However, for most production scenarios where performance matters, uasort() is the superior choice because it avoids unnecessary memory allocation.
It is also worth noting that if your subarrays contain keys other than name and age, you must ensure those keys remain intact. The sorting functions manipulate the order of elements but do not alter the internal structure of the subarrays themselves. A common pitfall occurs when developers attempt to sort using ksort() or asort(). These functions sort based on the keys of the current array level, which would fail here because the top-level keys (0, 1, 2) are numeric and unrelated to the alphabetical names you wish to sort by.
For projects built with the Laravel framework, there are additional considerations. While Laravel's collection facade provides powerful sorting methods like sortBy() or sortByDesc(), these operate on collections rather than raw arrays. If you are working within a controller or service layer where you have an array of resources, converting it to a collection via collect($data) allows you to leverage the fluent interface:
collect($data)->sortBy('name')->toArray();
This method is readable and less prone to typos in comparison logic, but it does carry the overhead of creating a collection object. For high-performance requirements or large datasets, sticking to uasort() with a raw array remains the most efficient solution.