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.

Watch a course Learn object oriented PHP

Use array_multisort()

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

<?php

$inventory = [ 
	[ 'type' => 'pork', 'price' => 5.43 ], 
	['type' => 'milk', 'price' => 2.9 ], 
	['type' => 'fruit', 'price' => 3.5] 
];

$price = [];

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

var_dump($inventory);

?>

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

Here is how to do that:

<?php

$inventory = [ 
	[ 'type' => 'pork', 'price' => 5.43 ], 
	['type' => 'milk', 'price' => 2.9 ], 
	['type' => 'fruit', 'price' => 3.5] 
];

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

array_multisort($price, SORT_DESC, $inventory);

var_dump($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:

<?php

$inventory = [ 
	[ 'type' => 'pork', 'price' => 5.43 ], 
	['type' => 'milk', 'price' => 2.9 ], 
	['type' => 'fruit', 'price' => 3.5] 
];

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

usort($inventory, 'invenDescSort');


var_dump($inventory);

?>

It will produce:

array(3) {
  [0] =>
  array(2) {
    'type' =>
    string(4) "pork"
    'price' =>
    double(5.43)
  }
  [1] =>
  array(2) {
    'type' =>
    string(5) "fruit"
    'price' =>
    double(3.5)
  }
  [2] =>
  array(2) {
    'type' =>
    string(4) "milk"
    'price' =>
    double(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.