Richard_Hollenbeck Posted December 6, 2013 Share Posted December 6, 2013 (edited) 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 December 6, 2013 by Richard_Hollenbeck Quote Link to comment https://forums.phpfreaks.com/topic/284588-finding-the-array-key-containing-highest-value/ Share on other sites More sharing options...
mac_gyver Posted December 6, 2013 Share Posted December 6, 2013 you would combine max() with array_search() should (untested) work - $key = array_search (max($arr), $arr); Quote Link to comment https://forums.phpfreaks.com/topic/284588-finding-the-array-key-containing-highest-value/#findComment-1461516 Share on other sites More sharing options...
.josh Posted December 6, 2013 Share Posted December 6, 2013 $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. Quote Link to comment https://forums.phpfreaks.com/topic/284588-finding-the-array-key-containing-highest-value/#findComment-1461517 Share on other sites More sharing options...
Solution .josh Posted December 6, 2013 Solution Share Posted December 6, 2013 Alternatively... $arr = array(15, 10, 25, 419, 65, 25); arsort($arr); echo key($arr); Quote Link to comment https://forums.phpfreaks.com/topic/284588-finding-the-array-key-containing-highest-value/#findComment-1461518 Share on other sites More sharing options...
Richard_Hollenbeck Posted December 6, 2013 Author Share Posted December 6, 2013 (edited) 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 December 6, 2013 by Richard_Hollenbeck Quote Link to comment https://forums.phpfreaks.com/topic/284588-finding-the-array-key-containing-highest-value/#findComment-1461520 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.