PHP: Sorting an array of arrays by key

Updated: January 11, 2024 By: Guest Contributor Post a comment

Introduction

Sorting arrays is a common task in programming, and PHP offers a variety of functions to accomplish this. Sometimes, the structures we work with are more complex than a simple one-dimensional array. Specifically, when you’re dealing with an array of arrays—also known as a multidimensional array—you might need to sort the data based on a specific key within the inner arrays. In PHP, this task can be achieved through several methods, including user-defined functions and built-in PHP functions. In this guide, we’ll cover how to sort an array of arrays by key using PHP.

Understanding the Array Structure

Before tackling the sorting functionality, it’s crucial to understand the array structure that we’re working with. An array of arrays is essentially a two-dimensional array where each element of the main array is an array itself. The sorting will be done on a key present in these sub-arrays.


$array = [
    ['id' => 10, 'name' => 'Alice', 'email' => '[email protected]'],
    ['id' => 20, 'name' => 'Bob', 'email' => '[email protected]'],
    // more sub-arrays
];

Now, let’s say we want to sort the array by the ‘id’ key. We can use several functions to do that.

Using array_multisort()

The array_multisort() function can be useful for sorting multiple arrays at once or sorting a multi-dimensional array by one or more dimensions. To sort an array of arrays by a single key, we can extract the values of that key into a separate array and use it as the sorting array along with array_multisort().


// Extract the id column
$ids = array_column($array, 'id');
// Sort the array by the ids
array_multisort($ids, SORT_ASC, $array);

However, this approach becomes tricky when working with associative arrays or when multiple sorting criteria are involved.

Using usort() for Custom Sorting

Another option is to use the usort() function, which lets you define a custom comparison function. This is particularly handy when you have complex sorting criteria or are dealing with associative arrays.


function sortByKey(&$array, $key, $sort_flag = SORT_REGULAR) {
    usort($array, function ($first, $second) use ($key, $sort_flag) {
        return $sort_flag === SORT_NUMERIC ? (int)$first[$key] - (int)$second[$key] : strcmp($first[$key], $second[$key]);
    });
}

// Now, sort the array by 'id'
sortByKey($array, 'id');

This code snippet introduces a user-defined function sortByKey() that takes the array reference, the key to sort by, and an optional sorting flag. The comparison function uses either numeric comparison or string comparison, based on the $sort_flag provided.

Using uasort() to Maintain Key Association

Yet another function we can use is uasort(), which is similar to usort(), but it maintains the association between keys and values in the array. This can be important when the keys of your array have significance, such as when they are meaningful indexes or identifiers.


uasort($array, function ($first, $second) use ($sort_key) {
    return $first[$sort_key] <=> $second[$sort_key];
});

In recent versions of PHP, you can use the spaceship operator (<=>) for simple comparison in uasort() or usort() functions. The spaceship operator returns -1, 0, or 1 when the first expression is less than, equal to, or greater than the second expression, respectively.

Sorting in Descending Order

To sort the arrays in descending order, you can simply reverse the comparison in your custom sorting function:


uasort($array, function ($first, $second) use ($sort_key) {
    return $second[$sort_key] <=> $first[$sort_key];
});

Advanced Sorting with array_multisort() and Multiple Keys

Let’s now look at a more advanced example where we sort by multiple keys using array_multisort(). We will create multiple arrays for each sorting criterion and then use them in the correct order within the function:


// Extract the columns
$ids = array_column($array, 'id');
$names = array_column($array, 'name');
// Sort by id ascending and then by name descending
array_multisort($ids, SORT_ASC, $names, SORT_DESC, $array);

This approach is powerful but requires you to be careful with the order in which you specify the arrays and their corresponding sort directions.

Conclusion

Sorting an array of arrays by a specific key can be a complex task, but PHP provides flexible functions to address this problem. Whether you have a simple scenario or need a customized sorting logic, there’s a suitable PHP function for you. Remember to use usort(), uasort(), or array_multisort() according to whether you need to maintain key association or have multiple sorting criteria. With these tools at your disposal, you are well on your way to mastering array sorting in PHP.

Remember to always test your sorting functions thoroughly to ensure they behave as expected across all cases you need to handle. Happy coding!