0

I am running into an ordering issue after an arsort() -

Array
(
  [22] => 20
  [11] => 20
  [17] => 18
  [5] => 18
  [35] => 17
  [34] => 17
  ...
)

After I am done working with the first set of data, I need to use an array_shift(as far as I know, its the only way to delete/pop the top element). However this causes the indices to seemingly reset to their original order.

Array
(
   [0] => 20
   [1] => 18
   [2] => 18
   [3] => 17
   [4] => 17
  ...
)

As you can see, the order of the values is retained, however the indices are reset. Is there any way to retain the original order of indices and values after performing a removal operation of the first element of the array? I am still a bit new to PHP so sorry if its an obvious solution.

  • Foreach the array and copy keys and their values to a new one starting from the 2nd item. – Alberto Nov 14 '18 at 13:36
  • 1
    @Alberto That sounds highly inefficient... – MonkeyZeus Nov 14 '18 at 13:37
  • 1
    Don't reverse sort (just use asort) and array_pop instead. – Progrock Nov 14 '18 at 13:40
  • I kinda need to, since I want to grab the absolute highest element in an array and its easier to keep them top down i would imagine. Current() would always point to the highest, arsort($array1Pref[$prefInd]) is based on value rather than keys/indicies – Random1144 Nov 14 '18 at 13:45
  • What @Progrock said. `asort()` -> `array_pop()` -> `end()` or `arsort()` – MonkeyZeus Nov 14 '18 at 13:59
  • thank you @MonkeyZeus, it worked pretty well, though because of the duplicate integers, some of the order got scrambled, though i think thats kind of unavoidable. Im concerned though that the asort will kill an incorrect duplicate number, ie 35->17, 34->17, and it choosing the 34 first. – Random1144 Nov 14 '18 at 14:51
  • The ordering of the keys is not guaranteed for [`arsort()`](http://php.net/manual/en/function.arsort.php) nor [`asort()`](http://php.net/manual/en/function.asort.php); see the `If two members compare as equal, their relative order in the sorted array is undefined.` note from both doc pages. The fact that they are in a desired order is complete coincidence and you should not rely on it. If the order of keys is important as a supplement to the order of values then check out https://stackoverflow.com/a/6611077 – MonkeyZeus Nov 14 '18 at 15:10
  • Right, I think doing 1 sort is probably the best I can do, so I will attempt to do 1x asort instead of fixing the arsort every iteration. Thank you Monkey – Random1144 Nov 14 '18 at 15:28
  • If it works for you then great but to save your own sanity you should assess what it is exactly that you need from these arrays. Based on your question and comments you have several disparate and non-compatible goals/solutions. – MonkeyZeus Nov 14 '18 at 16:36

0 Answers0