How can the PHP script be modified to ensure that only the best score from each user is displayed in the high score list?
To ensure that only the best score from each user is displayed in the high score list, we can modify the PHP script to check if a user's score is higher than their existing score before updating the high score list. This can be done by storing the best score for each user in a separate array and comparing new scores with the existing best scores.
// Sample code to display only the best score from each user in the high score list
$highScores = array(
"Alice" => 100,
"Bob" => 150,
"Alice" => 120,
"Charlie" => 200
);
$bestScores = array();
foreach ($highScores as $user => $score) {
if (!isset($bestScores[$user]) || $score > $bestScores[$user]) {
$bestScores[$user] = $score;
}
}
arsort($bestScores);
foreach ($bestScores as $user => $score) {
echo "$user: $score\n";
}
Keywords
Related Questions
- How can APIs be used to retrieve data from a remote website in PHP?
- How can one efficiently store multiple values in an array in PHP without overwriting the previous values?
- How can PHP be used to ensure accurate and reliable calculations when converting between different units of measurement, such as grams to kilograms or milliliters to liters?