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
]
asked Sep 22, 2009 at 17:08
1
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]
answered Sep 22, 2009 at 17:11
drAlberTdrAlberT
20.9k5 gold badges32 silver badges37 bronze badges
3
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.
answered Sep 22, 2009 at 17:17
I know it's already answered but here is a solution I find more elegant:
arsort[$array];
reset[$array];
echo key[$array];
and voila!
answered Dec 13, 2013 at 13:58
David 天宇 WongDavid 天宇 Wong
3,3584 gold badges33 silver badges47 bronze badges
1
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;
}
answered Jun 3, 2017 at 12:52
luchaninovluchaninov
6,6196 gold badges57 silver badges75 bronze badges
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;
}
answered Sep 22, 2009 at 17:11
AistinaAistina
12.2k12 gold badges67 silver badges88 bronze badges
1
My solution to get the higher key is as follows:
max[array_keys[$values['Users']]];
mtk
12.8k15 gold badges70 silver badges111 bronze badges
answered Mar 9, 2012 at 16:03
$newarr=arsort[$arr];
$max_key=array_shift[array_keys[$new_arr]];
answered Sep 22, 2009 at 17:14
dnagirldnagirl
20k13 gold badges79 silver badges119 bronze badges
Function taken from //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
answered Sep 22, 2009 at 17:29
3