1

I ran an election that has a variable number of winners for each category. (One category can have 3 winners, another 1 winner, another 2 winners, etc.)

Currently I am displaying the results like this:

foreach($newarray as $key => $value){

                echo $key . $value . “<br>”;
}

This returns

    Barack Obama 100
    Mitt Romney 100
    John Smith 94
    Jane Smith 85

What I need to do is have it echo out something if two of the values are the same based on that predetermined number. So, if the predetermined number was one, it would show this:

    Barack Obama 100 tie
    Mitt Romney 100 tie
    John Smith 94
    Jane Smith 85

If the predetermined number was two, it would show this since the second and third values aren’t the same:

    Barack Obama 100 winner
    Mitt Romney 100 winner
    John Smith 94
    Jane Smith 85

Thank you for your time.

  • Loop through the array twice. First count the number of ties for the winning score, and compare it to the number. Then do the print loop, and add the word `tie` or `winner` to the winners. – Barmar Apr 22 '13 at 21:46
  • Haha. Close - it is in the education realm but not homework. ;) – Adam Kazmierski Apr 22 '13 at 22:51

1 Answers1

0
$max = max($array);
$tie = count(array_keys($array,$max)) > $predeterminedNumber;
foreach($newarray as $key => $value){
     echo $key . $value . ($value==$max ? ($tie ? ' tie' :' winner') : ''). '<br>';
}

Allthough it becomes a bit more complex if you need the 3 winners don't necessarily have the same score:

$predefinedNumber = whatever;
arsort($array);

//first $predefinedNumber are either winners or tied.
$winners = array_slice($array,0,$predefinedNumber,true);

//the next entry determines whether we have ties
$next = array_slice($array,$predefinedNumber,1,true);

//active tie on entries with this value
$nextvalue = reset($next);

//the above 2 statements would be equivalent to (take your pick):
//$values = array_values($array);
//$nextvalue = $values[$predefinedNumber];


foreach($array as $key => $value){
   echo $key.' '.$value;
   if($value == $nextvalue){
     echo ' tie';
   } else if(isset($winners[$key])){
     echo ' winner';
   }
   echo '<br>';
}
Wrikken
  • 69,272
  • 8
  • 97
  • 136