How to Sort a Multidimensional Array by Value

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

Using the Spaceship Operator

Let’s start at PHP 7.

As a rule, for PHP 7 the spaceship operator is used like this:

<?php

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

?>

For extending it to multidimensional sorting, it is necessary to reference the second/third sorting elements in case the first is zero.

The clear example is demonstrated below:

<?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;
});

?>

Once you intend retaining the key associations, you can use uasort().

Using the Usort Function

Now, let’s check out another way of sorting a multidimensional array by value: the usort function.

It should be used only on PHP 5.2 or earlier versions.

In case you are still on such a version, you should first define a sorting function as follows:

<?php

function sortByOrder($a, $b)
{
  return $a['order'] - $b['order'];
}

usort($myArray, 'sortByOrder');

?>

Then, starting from PHP 5.3 version you can act like this:

<?php

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

?>

Defining the Spaceship Operator

The spaceship operator is used on PHP 7. It is considered a three-way comparison operator. It can perform greater than, less than, and equal comparison between two operands.

This operator can be used with arrays, floats, strings, objects, integers, and so on.

If values on either side are equal, it returns 0.

When the value on the left side is greater, it returns 1.

And, finally, if the value on the right is greater, it returns -1.