Jump to content

finding the array key containing highest value


Go to solution Solved by .josh,

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.

Edited by Richard_Hollenbeck
$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! :)

Edited by Richard_Hollenbeck
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.