views:

173

answers:

4

Hello guys I have an array like this

array={'a'=>'2','b'=>'5', 'c'=>'6', 'd'=>'6', 'e'=>'2'};

The array value might be different depending on the $_POST variables. My question is how to find the highest value in my array and return the index key. In my case, I need to get 'c' and 'd' and the value of 6. Not sure how to do this. Any helps would be appreciated. Thanks.

+3  A: 
$max  = max(array_values($array));
$keys = array_keys($array, $max);
mmattax
Thanks for the reply. +1
Jerry
You should not use `max(array_values($array))` inline. The OP only wants to get the value. Split it into two statements. `$keys` will only contain the keys.
Felix Kling
@Felix Kling - I didn't catch that thought he didn't care about the max number...
mmattax
A: 

Or this should do the magic, it would probably be faster than php built-in functions

$maxValue = -1;
$max = array();
foreach ($items as $key => $item) {
    if ($item == $maxValue) {
        $max[] = $key;
    } elseif ($item > $maxValue) {
        $max = array();
        $max[] = $key;
        $maxValue = $item;
    }
}
Mikulas Dite
Could you please explain why this probably is faster?
Christian Jonassen
Max, array_keys and array_values most probably all iterates through the array, my function just once. However, it's so fast anyway it doesn't matter.
Mikulas Dite
+1  A: 

Have a look at arsort which will sort an array in reverse order and maintain index association. So:

arsort($array);

This will end up with the largest values at the top of the array. Depending on what you need array_unique can remove duplicate values from your array.

Alistair
I need to get the duplicated value's index. But thx though. +1
Jerry
Sorting is O(n log n). This can be done in O(n).
Matthew Flaschen
+1  A: 
$array = array(
  'key1' => 22,
  'key2' => 17,
  'key3' => 19,
  'key4' => 21,
  'key5' => 24,
  'key6' => 8,
);

function getHighest($array)
{
   $highest = 0;
   foreach($array as $index => $value)
   {
      if(is_numeric($value) && $value > $highest)
      {
          $highest = $index;
      }
   }
   return $highest;
}

echo getHighest($array); //key5
RobertPitt
I need to get the duplicate key index. Good function though. +1
Jerry
changed to return the index key.
RobertPitt