1

This is my array :

10908  :int 110
10280  :int 175
10278  :int 585
10277  :int 3015
10275  :int 2835

The index is the ID of the element. I want to know which ID has the bigest value.

When I sort it I lose the value of the Index. How can I sort the index in function of the value?

CE_
  • 1,078
  • 2
  • 16
  • 33

3 Answers3

4

If you really need to sort it and want to keep the association between keys and values, use asort($array).

You can find a solution for your specific problem here: Return index of highest value in an array

Community
  • 1
  • 1
antesoles
  • 683
  • 6
  • 21
1

You need asort(), that sorts your array while keeping the keys.

And to get the highest key value, you can use max(array_keys($your_array)); regardless of the sort order of the array.

jeroen
  • 91,079
  • 21
  • 114
  • 132
1

@CE_ use asort() like below example:

    <?php
     $arr = array(10908 => 110, 10280 => 175, 10278 => 585, 10277 => 3015, 10275 => 2835);
    print_r($arr); //before sort
    asort($arr);
    print_r($arr); // after sort

This asort() function sort array along with the index

lazyCoder
  • 2,544
  • 3
  • 22
  • 41
  • I'd like to suggest that you remove the closing `?>` php tag... It is generally considered bad style since it causes endless issues for nothing... It is typically not required, except if you want to terminate php interpretation in the middle of some file. – arkascha Jan 20 '17 at 14:09
  • i know but i follow the syntax rules, i know ?> not required but its my good habbit – lazyCoder Jan 20 '17 at 14:15
  • Actually it is _not_ a good habit, since it causes issues without offering any benefit. And the "syntax rules" do _not_ require you to close a php block in general... – arkascha Jan 20 '17 at 14:18