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 is the best way to read all data of an entry in a PHP SimpleXML object in a specific order?
- What debugging techniques can be used to troubleshoot cURL download issues in PHP, such as using CURLOPT_PROGRESSFUNCTION or packet dumps?
- How can the use of command-line arguments enhance the functionality of PHP scripts?