Looping through Associative Array as many times as the key

27 views Asked by At

I'm trying to loop through an Associative Array but instead of 10 times, it loops trhrough lots of times. Also, I'm trying to keep track of how many answers the user answered correctly. I'd use post but this is cmd php so that won't be possible.

<?php
$countries = [
"Japan" => "Tokyo",
"Mexico" => "Mexico City",
"USA" => "Washington D.C.",
"India" => "New Delhi",
"Zuid-Korea" => "Seoul",
"China" => "Peking",
"Nigeria" => "Abuja",
"Argentina" => "Buenos Aires",
"Egypt" => "Cairo",
"UK" => "London"
];
echo "Weet jij de hoofdsteden van alle landen?" . PHP_EOL;
for ($i = 0; $i <= count($countries); $i++) {
    foreach ($countries as $key => $value) {
        echo "Wat is de hoofdstad van " . $key . "?" . PHP_EOL;
        $answer = readline();
        if ($answer !== $value) {
            echo "Helaas!" . PHP_EOL;
        } else {
            echo "Correct!" . PHP_EOL;
        }
    }
}
echo "Je hebt " . 0 . " goede antwoorden.";
echo "Je hebt " . 10 . " van de 10 goed.";
?>
1

There are 1 answers

0
Janus On

Looks like I've played myself and added a for loop for naught.

<?php
$countries = [
"Japan" => "Tokyo",
"Mexico" => "Mexico City",
"USA" => "Washington D.C.",
"India" => "New Delhi",
"Zuid-Korea" => "Seoul",
"China" => "Peking",
"Nigeria" => "Abuja",
"Argentina" => "Buenos Aires",
"Egypt" => "Cairo",
"UK" => "London"
];
echo "Weet jij de hoofdsteden van alle landen?" . PHP_EOL;
    foreach ($countries as $key => $value) {
        echo "Wat is de hoofdstad van " . $key . "?" . PHP_EOL;
        $answer = readline();
        if ($answer !== $value) {
            echo "Helaas!" . PHP_EOL;
        } else {
            echo "Correct!" . PHP_EOL;
        }
    }
?>