0

Assuming we have the following array:

$edibles = [

    ['Apple', 250],
    ['Pear', 300],
    ['Cherry', 270],
    ['Tomato', 300],
    ['Carrot', 240],
    ['Potato', 170]

];

What would be the best way to sort those items by item[1]?

There are no array keys present which is why the google results didn't help me very much.

Thank you in advance!

Arno Nymo
  • 39
  • 9

2 Answers2

3

Use usort:

usort( $edibles, function ( $a, $b ) {
  return $a[1] - $b[1];
} );
Paul
  • 139,544
  • 27
  • 275
  • 264
2

You can extract the values from index 1, sort that and then sort the original on that using array_multisort():

array_multisort(array_column($edibles, 1), SORT_ASC, $edibles);
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87