W3docs

How to Sort a Multidimensional Array by Value

In this short tutorial, you will learn the most efficient ways to easily sort a multidimensional array by value using PHP. Just follow the steps below.

In this snippet, we are going to show you how to sort a multidimensional array by value in the most straightforward and effective ways.

Understanding the Spaceship Operator

The spaceship operator (<=>) was introduced in PHP 7. It is a three-way comparison operator that performs greater than, less than, and equal comparisons between two operands. It works with arrays, floats, strings, objects, integers, and more.

  • If values on either side are equal, it returns 0.
  • If the value on the left side is greater, it returns 1.
  • If the value on the right side is greater, it returns -1.

Using the Spaceship Operator

For PHP 7 and later, the spaceship operator is typically used like this:

<?php
usort($myArray, function ($a, $b) {
  return $a['order'] <=> $b['order'];
});
?>

To extend this to multidimensional sorting, reference the second or third sorting elements if the first comparison returns zero:

<?php
usort($myArray, function ($a, $b) {
  $retval = $a['order'] <=> $b['order'];
  if ($retval == 0) {
    $retval = $a['suborder'] <=> $b['suborder'];
    if ($retval == 0) {
      $retval = $a['details']['subsuborder'] <=> $b['details']['subsuborder'];
    }
  }
  return $retval;
});
?>

If you need to retain the original key associations, use uasort() instead of usort().

Pre-PHP 7 Approach

Before PHP 7, developers typically used subtraction for numeric sorting. Define a sorting function as follows:

<?php
function sortByOrder($a, $b)
{
  return $a['order'] - $b['order'];
}
usort($myArray, 'sortByOrder');
?>

Starting from PHP 5.3, you can also use an anonymous function:

<?php
usort($myArray, function ($a, $b) {
  return $a['order'] - $b['order'];
});
?>