tags:

views:

435

answers:

5

From an array that looks something like the following, how can I get the index of the highest value in the array. For the array below, the desired result would be '11'.

Array (

[11] => 14
[10] => 9
[12] => 7
[13] => 7
[14] => 4
[15] => 6

)

+13  A: 

My solution is:

$maxs = array_keys($array, max($array))

Note:
this way you can retrieve every key related to a given max value.

If you are interested only in one key among all simply use $maxs[0]

AlberT
Perfect. Thank you!
Deca
A: 

Something like this should do the trick

function array_max_key($array) {
  $max_key = -1;
  $max_val = -1;

  foreach ($array as $key => $value) {
    if ($value > $max_val) {
      $max_key = $key;
      $max_val = $value;
    }
  }

  return $max_key;
}
Aistina
Better use the first item’s key and value as the default value.
Gumbo
A: 
$newarr=arsort($arr);
$max_key=array_shift(array_keys($new_arr));
dnagirl
+2  A: 
<?php

$array = array(11 => 14,
               10 => 9,
               12 => 7,
               13 => 7,
               14 => 4,
               15 => 6);

echo array_search(max($array), $array);

?>

array_search() Return Values

Returns the key for needle if it is found in the array, FALSE otherwise.

If needle is found in haystack more than once, the first matching key is returned. To return the keys for all matching values, use array_keys() with the optional search_value parameter instead.

Andrejs Cainikovs
A: 

Function taken from http://www.php.net/manual/en/function.max.php

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

$arr = array (
    '11' => 14,
    '10' => 9,
    '12' => 7,
    '13' => 7,
    '14' => 4,
    '15' => 6
);

die(var_dump(max_key($arr)));

Works like a charm

Timur Asaliev
Not to speak about performance. Foreaching through array, checking max value every time is even worse than "bad practice".
bisko
I mentioned its not my implementation. It was a quick and dirty copy/paste that the OP obviously couldn't do himself, mister.
Timur Asaliev