Cloudkiller
Cloudkiller

Reputation: 1636

Getting an array key using the max() function

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.

Upvotes: 14

Views: 19488

Answers (3)

Funcraft
Funcraft

Reputation: 1709

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

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

Upvotes: 8

kravemir
kravemir

Reputation: 11016

array_search function would help you.

$returnThis = array_search(max($arrCompare),$arrCompare);

Upvotes: 25

Evan Mulawski
Evan Mulawski

Reputation: 55334

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/

Upvotes: 4

Related Questions