This post will discuss how to sort an array of associative arrays by multiple fields in PHP.

1. Using array_multisort() function

You can in-place sort multidimensional arrays in PHP using array_multisort() function, by one or more fields. It takes an array to be sorted, optionally followed by sort order and sort options, followed by more arrays, their sort order, and their sort options.

For example, the following one-liner sorts an array of associative arrays, $users, by its age field. It uses array_column() function to get an array of values representing the age column from $users array.

Download  Run Code

 
The array_column() function is only available since PHP 5.5.0. Prior to that, you can use foreach instead to obtain an array of values representing a column.

Download  Run Code

 
Note: Prior to PHP 8.0.0, if the comparison function identified two elements as equal, their relative order in the sorted array was undefined. Starting with PHP 8.0.0, the equal elements preserve their relative order.

2. Using usort() function

Like other programming languages like C++ and Java, PHP provides the ability to sort an array using a comparison function to determine the sorted order. This can be done with usort() function in PHP, which in-place sorts the given array by values using a user-defined comparison function. The PHP documentation states – “The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.”

The usort() function can be used with anonymous functions such as those listed below. It sorts an array of associative arrays $users by its age field.

Download  Run Code

 
Anonymous functions are introduced with PHP 5.3. If your project is still on PHP 5.2 or less, you can write a comparison function and pass it to usort():

Download  Run Code

 
Since PHP 7, you can simplify the ordering callbacks by using the spaceship operator to compare two elements. The spaceship operator op1 <=> op2 returns 0 if both operands are equal, 1 if the left operand is greater than the right operand, and -1 if the right operand is greater than the left operand.

Download  Run Code

 
The spaceship operator allows straightforward comparisons across multiple attributes. For example, the following program will sort $users array first by age, then by name if the age matches.

Download  Run Code

 
Note: Prior to PHP 8.0.0, if the comparison function determined that two elements were equal, their relative order in the resulting sorted array was undefined. You can use the uasort() function to retain their original order.

That’s all about sorting an array of associative arrays by multiple fields in PHP.