14

I'm using the max() function to find the largest value in an array. I need a way to return the key of that value. I've tried playing with the array_keys() function, but all I can get that to do is return the largest key of the array. There has to be a way to do this but the php manuals don't mention anything.

Here's a sample of the code I'm using:

$arrCompare = array('CompareOne' => $intOne,
                    'CompareTwo' => $intTwo,
                    'CompareThree' => $intThree,
                    'CompareFour' => $intfour);

$returnThis = max($arrCompare);

I can successfully get the highest value of the array, I just can't get the associated key. Any ideas?


Edit: Just to clarify, using this will not work:

$max_key = max( array_keys( $array ) );

This compares the keys and does nothing with the values in the array.

2
  • It seems odd that array_keys() doesn't help you. Commented Aug 15, 2011 at 18:12
  • @Dor: Using array_keys compares the key values. Commented Aug 15, 2011 at 18:13

3 Answers 3

25

array_search function would help you.

$returnThis = array_search(max($arrCompare),$arrCompare);
Sign up to request clarification or add additional context in comments.

Comments

8

If you need all keys for max value from the source array, you can do:

$keys = array_keys($array, max($array));

2 Comments

Prefer this one, though it's perhaps less obvious than array_search(). I didn't even know that array_keys could take a $search_value as its second argument!
This returned the SECOND highest key. I went with this answer and that worked in my case : stackoverflow.com/questions/6126066/…
4

Not a one-liner, but it will perform the required task.

function max_key($array)
{
    $max = max($array);
    foreach ($array as $key => $val)
    {
        if ($val == $max) return $key;
    }
}

From http://cherryblossomweb.de/2010/09/26/getting-the-key-of-minimum-or-maximum-value-in-an-array-php/

3 Comments

Don't recalculate max($array) in each loop iteration - I very much doubt the PHP runtime is smart enough to hoist that out of the loop
@Adam: Wow. Thanks a bunch. I can't believe I missed that when I was reading it!
I tested this and it works but it is a bit verbose. I'm going to go with Miro's solution, but thank anyway.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.