开发者

How to search for largest value in array, and return associated key in PHP

I'd like to be able to return the number 15 in this case:

Array ( [420315] => 1 [21714] => 1 [20] => 1 [1] => 1 [18] 开发者_StackOverflow社区=> 1 [241] => 2 [15] => 5 [1038401] => 1 [114] => 1 [293641] => 1 [387] => 1 [232] => 1 [11368] => 1 [9225] => 1 [100] => 1 [9254] => 1 [15326] => 1 [9246] => 1 [97] => 1 [9241] => 1 [14242] => 1 [9456] => 1 [366] => 1 [130] => 1 [373] => 1 ) 


Use this

array_keys($array, max($array));

Reference for those 2 functions
http://www.php.net/manual/en/function.array-keys.php
http://php.net/manual/en/function.max.php


$maxval = -1;
$maxkey = 0;
foreach ($arr as $key=>$val) {
   if ($val >= $maxval) {
       $maxval = $val;
       $maxkey = $key;
   }
}
return $maxkey;

Assuming the array is positive. Otherwise, use the appropriate starting value for $maxval.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜