返回数组中最大值的索引

从一个看起来像下面这样的数组中,我如何得到数组中最高值的索引。对于下面的数组,所需的结果将是“11”。

Array (
[11] => 14
[10] => 9
[12] => 7
[13] => 7
[14] => 4
[15] => 6
)
118964 次浏览

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;
}
$newarr=arsort($arr);
$max_key=array_shift(array_keys($new_arr));
<?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

My solution to get the higher key is as follows:

max(array_keys($values['Users']));

I know it's already answered but here is a solution I find more elegant:

arsort($array);
reset($array);
echo key($array);

and voila!

Other answers may have shorter code but this one should be the most efficient and is easy to understand.

/**
* Get key of the max value
*
* @var array $array
* @return mixed
*/
function array_key_max_value($array)
{
$max = null;
$result = null;
foreach ($array as $key => $value) {
if ($max === null || $value > $max) {
$result = $key;
$max = $value;
}
}


return $result;
}