Sort PHP multi-dimensional array based on value in inner array?

Sort PHP multi-dimensional array based on value in inner array?

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

Stefan Bogdanescu

Founder & Senior Architect

Sorting Multi-Dimensional Arrays in PHP by Nested Keys

You are attempting to sort an array of associative arrays where the data you care about resides deep within the structure. Your specific case involves a top-level index mapping to a sub-array containing type and name. You want to reorder these outer indices based on the string value found in the name key of the nested array.

The confusion often stems from mixing up sorting algorithms that operate on keys versus those that operate on values, or attempting to sort numeric arrays as if they were associative maps. In your example, $mydata is numerically indexed (0, 1, 2), but you are trying to influence the order based on the string content in $mydata[$i]['name'].

The built-in ksort() and asort() functions are not suitable here because they sort by keys or values of the current array element, not a nested property. They will likely fail to produce the desired result or throw warnings if the structure isn't exactly what you expect. Similarly, usort() is the correct tool for custom logic, but your initial implementation contains a critical logical error regarding data types.

The Type Mismatch in Your Comparison Function

Your attempt used usort with a callback that subtracted the names:

function cmp($a, $b) {
    return $b['name'] - $a['name'];
}
usort($mydata, "cmp");

This approach fails immediately because $a['name'] and $b['name'] are strings (e.g., "A-Name", "C-Name"). Subtracting strings in PHP triggers a type juggling process where the string is cast to an integer. If the string does not start with a number, it becomes 0. Consequently, every comparison returns 0, telling PHP that all elements are equal. This results in the sort order remaining unchanged or behaving unpredictably depending on internal implementation details.

To sort strings correctly, you must compare them lexicographically rather than arithmetically. You have two primary options for implementing this logic within usort.

Option 1: The Standard String Comparison

The most robust way to handle string sorting is using the strict equality operator (===) combined with a conditional check. This ensures that "A-Name" is correctly identified as coming before "B-Name".

function cmp($a, $b) {
    if ($a['name'] == $b['name']) {
        return 0;
    }
    return ($a['name'] < $b['name']) ? -1 : 1;
}

usort($mydata, 'cmp');

This function returns -1 if the first element should come before the second, 1 if it should come after, and 0 if they are equal. This is the standard contract for comparison callbacks in PHP. Note that using loose comparison (==) inside the equality check can sometimes lead to unexpected results with mixed types, so strictly checking string values or casting them explicitly is often safer in production environments.

Option 2: The Ternary Shortcut

If you prefer a more concise syntax and are confident your data contains only strings, you can use a ternary operator directly inside the return statement. This reduces code clutter while maintaining the correct logic for ascending order.

usort($mydata, function ($a, $b) {
    return strcmp($a['name'], $b['name']);
});

Here, strcmp() is a built-in PHP function specifically designed to compare two strings case-sensitively and return an integer indicating their relative order. It handles the logic of returning negative, positive, or zero values automatically. This approach removes the need to write out the conditional logic manually and reduces the chance of syntax errors in your comparison block.

When to Consider Laravel Collections

If you are working within a Laravel application, you might find yourself asking if there is an even easier way. In that specific context, using the LaravelCompany ecosystem or standard Laravel helpers allows you to offload this logic entirely. You can convert the raw array into a Collectable instance and chain sorting methods directly:

use Illuminate\Support\Collection;

$collection = collect($mydata);
$sorted = $collection->sortBy('name');

return $sorted->toArray();

This syntax is significantly more readable than defining a separate comparison function, especially if you are already familiar with Laravel's fluent interface. However, the raw usort approach remains essential when dealing with legacy code or standalone PHP scripts where loading the framework overhead is undesirable.

Final Verification

After running the sort, always verify the result by printing the array again. Remember that sorting modifies the original array in place unless you assign the output of usort() to a new variable (though usort returns the number of elements swapped and does not return the sorted array itself). If your downstream logic expects a specific order, ensure the sort happens immediately before you generate your response or save the data.

Our network