I'm using the max() function to find the largest value in an array. I need a way to return the key of that value. I've tried playing with the array_keys() function, but all I can get that to do is return the largest key of the array. There has to be a way to do this but the php manuals don't mention anything.
我正在使用max()函数来查找数组中的最大值。我需要一种方法来返回该值的键。我尝试过使用array_keys()函数,但我能做到的就是返回数组中最大的键。必须有一种方法来做到这一点,但PHP手册没有提到任何东西。
Here's a sample of the code I'm using:
这是我正在使用的代码示例:
$arrCompare = array('CompareOne' => $intOne,
'CompareTwo' => $intTwo,
'CompareThree' => $intThree,
'CompareFour' => $intfour);
$returnThis = max($arrCompare);
I can successfully get the highest value of the array, I just can't get the associated key. Any ideas?
我可以成功获得数组的最高值,我只是无法得到相关的密钥。有任何想法吗?
Edit: Just to clarify, using this will not work:
编辑:只是为了澄清,使用它将无法正常工作:
$max_key = max( array_keys( $array ) );
This compares the keys and does nothing with the values in the array.
这比较了键,并且对数组中的值没有任何作用。
3 个解决方案
#1
25
array_search function would help you.
array_search函数可以帮到你。
$returnThis = array_search(max($arrCompare),$arrCompare);
#2
7
If you need all keys for max value from the source array, you can do:
如果您需要源数组中所有键的最大值,您可以执行以下操作:
$keys = array_keys($array, max($array));
#3
4
Not a one-liner, but it will perform the required task.
不是单行,但它将执行所需的任务。
function max_key($array)
{
$max = max($array);
foreach ($array as $key => $val)
{
if ($val == $max) return $key;
}
}
From http://cherryblossomweb.de/2010/09/26/getting-the-key-of-minimum-or-maximum-value-in-an-array-php/
#1
25
array_search function would help you.
array_search函数可以帮到你。
$returnThis = array_search(max($arrCompare),$arrCompare);
#2
7
If you need all keys for max value from the source array, you can do:
如果您需要源数组中所有键的最大值,您可以执行以下操作:
$keys = array_keys($array, max($array));
#3
4
Not a one-liner, but it will perform the required task.
不是单行,但它将执行所需的任务。
function max_key($array)
{
$max = max($array);
foreach ($array as $key => $val)
{
if ($val == $max) return $key;
}
}
From http://cherryblossomweb.de/2010/09/26/getting-the-key-of-minimum-or-maximum-value-in-an-array-php/