ecopetition Posted February 5, 2012 Share Posted February 5, 2012 Hi all, I have the following array, which represents option_id => number_of_votes Array ( [3] => 4 [5] => 5 [2] => 11 ) Is it possible to look at the value side of the array and neglect the smallest values, and pick a vote winner? Also, if we get the case: Array ( [3] => 4 [5] => 11 [2] => 11 ) can we pick a random winner between option 5 and option 2? Thanks so much for all your help, let me know if more information will be useful. Quote Link to comment https://forums.phpfreaks.com/topic/256427-getting-maximum-value-of-array/ Share on other sites More sharing options...
noXstyle Posted February 5, 2012 Share Posted February 5, 2012 <?php function getMax($a) { $max = array_keys($a, max($a)); if(count($max)>1) { $r = rand(0, count($max)-1); return array($max[$r] => $a[$max[$r]]); } return array($max[0]=>$a[$max[0]]); } Will return array in which the key is option_id and value is number of votes. Edit: You can also simplify the function by removing the if statement. In this case there will be a rand() call even if a single max value is found. function getMax($a) { $max = array_keys($a, max($a)); $r = rand(0, count($max)-1); return array($max[$r] => $a[$max[$r]]); } Quote Link to comment https://forums.phpfreaks.com/topic/256427-getting-maximum-value-of-array/#findComment-1314736 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.