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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.