How to sort an array of associative arrays by value of a given key in PHP?

Spread the love

Sometimes, we want to sort an array of associative arrays by value of a given key in PHP.

In this article, we’ll look at how to sort an array of associative arrays by value of a given key in PHP.

How to sort an array of associative arrays by value of a given key in PHP?

To sort an array of associative arrays by value of a given key in PHP, we can use the usort function.

For instance, we write

usort($inventory, function ($item1, $item2) {
    return $item1['price'] <=> $item2['price'];
});

to call usort to sort the $inventory associative array by the value of the value with key 'price' of each entry.

We can sort in descending order by flipping the operands.

Conclusion

To sort an array of associative arrays by value of a given key in PHP, we can use the usort function.

Leave a Reply

Your email address will not be published. Required fields are marked *