w3docs logo
  1. Snippets
  2. PHP
  3. 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

In this article, we will cover a common issue: how to sort an array of arrays by the value of a given key with PHP.

Below, you can find the handiest methods with their examples.

Use array_multisort()

Let’s see how to use the array_multisort() function:

$price = array(); foreach ($inventory as $key => $row) { $price[$key] = $row['price']; } array_multisort($price, SORT_DESC, $inventory);

In PHP 5.5 and above versions, array_column() can be used instead of foreach.

Here is how to do that:

$price = array_column($inventory, 'price'); array_multisort($price, SORT_DESC, $inventory);

Use Custom Comparison Function

Another option is using the custom comparison function. It is a pretty quick and handy solution to the problem.

Here is the example:

function invenDescSort($item1,$item2) { if ($item1['price'] == $item2['price']) return 0; return ($item1['price'] < $item2['price']) ? 1 : -1; } usort($inventory,'invenDescSort'); print_r($inventory);

It will produce:

Array ( [0] => Array ( [type] => pork [price] => 5.43 ) [1] => Array ( [type] => fruit [price] => 3.5 ) [2] => Array ( [type] => milk [price] => 2.9 ) )

In this tutorial, we represented two methods of sorting an array of arrays by the value of a given key with PHP.

However, there are other possible solutions to the issue. You can find more information and options on this page.

Do you find this helpful?