-1

Consider this array:

Array( [Wingspan] => 5 
[Scythe] => 1 
[Spirit Island] => 2 
[Everdell] => 1)

How can I sort this array with the highest value(5) as first, then 2 then lowest (1) as the last? I used this:

print_r(rsort($_POST['item']), SORT_NUMERIC);

But I get this:

Array
(
    [0] => 2
    [1] => 1
    [2] => 1
    [3] => 1
)

It changes the key, but this is wrong. I expect to get this:

Array( [Wingspan] => 5 
[Spirit Island] => 2 
[Scythe] => 1 
[Everdell] => 1)

I searched and found this: Sort an Array by numerical value but that did not help.

  • The result you've shown doesn't correspond with the sample array. Please note that sorting functions don't return the sorted array, so you can't feed that function into a `print_r` to see the sorted array. You just call `rsort` then dump you array after that. – El_Vanja May 01 '21 at 14:18
  • 1
    Does this answer your question? [How can I sort arrays and data in PHP?](https://stackoverflow.com/questions/17364127/how-can-i-sort-arrays-and-data-in-php) – El_Vanja May 01 '21 at 14:21
  • The linked question explains all the variants of sorting, should you ever need a different algorithm. – El_Vanja May 01 '21 at 14:22

1 Answers1

1

Use the method

arsort($_POST['item'])

instead of rsort. rsort only works for simple arrays, not for associative ones. But anyways usually if the order of te items matters to you, probably an associative array is not the best choice. You could use a simple array with objects inside containing the values and the keys at once

Richard Nagy
  • 121
  • 6