Sometimes, we want to sort a multi-dimensional array by value with PHP.
In this article, we’ll look at how to sort a multi-dimensional array by value with PHP.
How to sort a multi-dimensional array by value with PHP?
To sort a multi-dimensional array by value with PHP, we can use the usort
function.
For instance, we write
usort($arr, function($a, $b) {
return $a['order'] - $b['order'];
});
to call usort
with the $arr
array that we want to sort in place.
The 2nd argument is a function that returns a number.
If it’s positive, then we put $a
before $b
.
If it’s negative, then we put $b
before $a
.
And if it’s 0, we keep the order the way it is.
We sort by the value of the 'order
entry in $a
and $b
in ascending order, so we subtract the values of the 'order'
field in the associative array.
Conclusion
To sort a multi-dimensional array by value with PHP, we can use the usort
function.