2
Array (
  [0] => Array (
    [2] => 9.6
  )
  [1] => Array (
    [497] => 11.666666666667
  )
  [2] => Array (
    [451] => 34
  )
  [3] => Array (
    [459] => 8.8
  )
  [4] => Array (
    [461] => 22.5 
  )
)

I have this array.

How can I sort it by number value?

I tried

usort($array, function ($a, $b)
{
    return $a[0] < $b[0];
});

But doesn't work.

Phil
  • 157,677
  • 23
  • 242
  • 245
Utku Dalmaz
  • 9,780
  • 28
  • 90
  • 130

2 Answers2

1

First things first... from the manual

value_compare_func
The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

Emphasis on the "integer" part.

From PHP 7, you can use the spaceship operator for this.

You need to do some extra work though to address your non-sequential array keys. You can get the first value using reset()

usort($array, function($a, $b) {
    return reset($b) <=> reset($a);
});

Demo ~ https://3v4l.org/uni3v (doesn't work in PHP 5.x)


The pre PHP 7 version can be achieved with a simple subtraction. For example

return reset($b) - reset($a);
Phil
  • 157,677
  • 23
  • 242
  • 245
0

Try this:

$numbers = [1, 3, 2];

usort($numbers, function ($a, $b) {
    return $a < $b ? 1 : ($a === $b ? 0 : -1);
});

print_r($numbers);

Result is:

Array
(
    [0] => 3
    [1] => 2
    [2] => 1
)
Marcel
  • 664
  • 6
  • 4