How can the code for the Rangliste Klasse be simplified and improved in terms of efficiency and readability?
The code for the Rangliste Klasse can be simplified and improved by using built-in PHP functions to sort the array of players based on their scores. This will make the code more efficient and readable. Additionally, we can use a foreach loop to iterate over the sorted array and display the player's rank along with their name and score.
class Rangliste {
private $players = [];
public function addPlayer($name, $score) {
$this->players[] = ['name' => $name, 'score' => $score];
}
public function displayRanking() {
usort($this->players, function($a, $b) {
return $b['score'] - $a['score'];
});
$rank = 1;
foreach ($this->players as $player) {
echo "Rank $rank: {$player['name']} - Score: {$player['score']}<br>";
$rank++;
}
}
}
$rangliste = new Rangliste();
$rangliste->addPlayer('Alice', 100);
$rangliste->addPlayer('Bob', 80);
$rangliste->addPlayer('Charlie', 120);
$rangliste->displayRanking();
Related Questions
- What common pitfalls should be avoided when passing variables from one PHP script to another for database queries?
- Are there best practices for securing sensitive information, such as usernames, when sending emails through PHPMailer?
- How should the separation of concerns be maintained between Model, View, and Controller in PHP applications?