tags:

views:

33

answers:

2

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

Array ( [420315] => 1 [21714] => 1 [20] => 1 [1] => 1 [18] => 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 ) 
+1  A: 
$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.

Borealid
What if there're more than one maximun value in the `array`. Like `array( 0 => 1, 1 => 1, 2 => 2, 3 => 2 )`;
Bang Dao
@Bang Dao: If you want the last one, use `>=`. If you want the first one, use `>`.
Borealid
+4  A: 

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

Bang Dao
Thanks so much!
patrick