Jump to content

finding the array key containing highest value


Richard_Hollenbeck

Recommended Posts

I am NOT looking for max().

 

In an array, I'm trying to find the key with the highest value, not the highest value itself.

For example,

$arr = array(15, 10, 25, 419, 65, 25);
echo max($arr); // Nope.  Not what I'm looking for. Wrong answer.

echoes the value 419. I know. Thanks. That's not what I want.

We all know that in the above example, $arr[3]==419. I got that.  But I am not looking for the 419. I'm looking for the 3.

 

Thanks for any help.

$arr = array(15, 10, 25, 419, 65, 25);
echo array_search(max($arr),$arr);
note that if the max number appears more than once, the first matched index will return. You didn't really mention what should happen in this event, but if you need all of the indexes for the highest value then you should use array_keys instead. And if you need the last index, use array_keys and then array_pop.

Thanks to both of you.  mac_gyver, your help is awesome as it always has been. Both of the first two answers work perfectly.

 

 

However, now that Josh posted another reply that sorts the whole array:

 

Alternatively...
 

$arr = array(15, 10, 25, 419, 65, 25);
arsort($arr);
echo key($arr);

 

I am even closer to where I need to go than I ever anticipated.

 

You both gave the best answer, but I can only vote on one "best answer."  So I have to pick this one for the additional sort.  Thanks to you both! :)

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.