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
)
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
)
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]
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;
}
<?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.
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