user3233074
user3233074

Reputation: 529

Getting Highers and Same score in array

$Ascore = 30;
$Bscore = 30;
$Cscore = 20;
$Dscore = 20;

 $score = array(
            'As' => $Ascore,
            'Bs' => $Bscore,
            'Cs' => $Cscore,
            'Ds' => $Dscore
);

$match = 0;
foreach($score as $key => $val){
if($val > $match){
    $match = $val;
}
}
echo $match;

my intention is to find highers score that match , for example highers score = 30 ,As and Bs matched , echo out As = 30 , Bs = 30. so if any 2 of the highers score in the array and having the same highers score, echo both of them. only echo them out if they have same highers score.

Upvotes: 1

Views: 47

Answers (1)

Luke
Luke

Reputation: 1724

Try the following:

$scores = [
    'As' => $Ascore,
    'Bs' => $Bscore,
    'Cs' => $Cscore,
    'Ds' => $Dscore,
];
$highest = max($scores);
foreach ($scores as $key => $val)
    if ($val === $highest)
        echo $key . ' = ' . $val . ', ';

Alternate if the trailing comma IS an issue:

$highest = max($scores);
$victors = [];
foreach ($scores as $key => $val)
    if ($val === $highest)
        $victors[] = $key . ' = ' . $val;

echo implode(', ', $victors);

Upvotes: 2

Related Questions