Jump to content

Getting maximum value of array


ecopetition

Recommended Posts

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.

Link to comment
https://forums.phpfreaks.com/topic/256427-getting-maximum-value-of-array/
Share on other sites

<?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]]);
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.