Given this array:
$inventory = array(
array("type"=>"fruit", "price"=>3.50),
array("type"=>"milk", "price"=>2.90),
array("type"=>"pork", "price"=>5.43),
);
I would like to sort $inventory
's elements by price to get:
$inventory = array(
array("type"=>"pork", "price"=>5.43),
array("type"=>"fruit", "price"=>3.50),
array("type"=>"milk", "price"=>2.90),
);
How can I do this?
Since your array elements are arrays themselves with string keys, your best bet is to define a custom comparison function. It's pretty quick and easy to do. Try this:
Produces the following:
PHP 7+
As of PHP 7, this can be done concisely using
usort
with an anonymous function that uses the spaceship operator to compare elements.You can do an ascending sort like this:
Or a descending sort like this:
To understand how this works, note that
usort
takes a user-provided comparison function that must behave as follows (from the docs):And note also that
<=>
, the spaceship operator,which is exactly what
usort
needs. In fact, almost the entire justification given for adding<=>
to the language in https://wiki.php.net/rfc/combined-comparison-operator is that itPHP 5.3+
PHP 5.3 introduced anonymous functions, but doesn't yet have the spaceship operator. We can still use
usort
to sort our array, but it's a little more verbose and harder to understand:Note that although it's fairly common for comparators dealing with integer values to just return the difference of the values, like
$item2['price'] - $item1['price']
, we can't safely do that in this case. This is because the prices are floating point numbers in the question asker's example, but the comparison function we pass tousort
has to return integers forusort
to work properly:This is an important trap to bear in mind when using
usort
in PHP 5.x! My original version of this answer made this mistake and yet I accrued ten upvotes over thousands of views apparently without anybody noticing the serious bug. The ease with which lackwits like me can screw up comparator functions is precisely the reason that the easier-to-use spaceship operator was added to the language in PHP 7.Complete Dynamic Function I jumped here for associative array sorting and found this amazing function on http://php.net/manual/en/function.sort.php. This function is very dynamic that sort in ascending and descending order with specified key.
Simple function to sort an array by a specific key. Maintains index association
outputs:
While others have correctly suggested the use of
array_multisort()
, for some reason no answer seems to acknowledge the existence ofarray_column()
, which can greatly simplify the solution. So my suggestion would be: