Mo Martin
Mo Martin

Reputation: 207

Associative Array + Foreach statement -- undefined variable

I'm really struggling with making this work, I have looked at guides but I can't seem to see the difference between mine and theirs, other than how the array is laid out.

<?php
$country = array('England' => "London", 'Scotland' => "Edinburgh", 'France' => "Paris");

foreach ($capitals as $country=>$capital) {
echo "The capital of $country is $capital";
}

?>

All I want it to do is say the country and its capital.

error code --

Notice: Undefined variable: capitals in C:\xampp\htdocs\foreach.php on line 4

Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\foreach.php on line 4

Thanks in advance.

Upvotes: 0

Views: 277

Answers (2)

Rizier123
Rizier123

Reputation: 59701

Change your code to this:

(I change the array name from country to capitals)

<?php

    $capitals = array('England' => "London", 'Scotland' => "Edinburgh", 'France' => "Paris");

    foreach ($capitals as $country=>$capital) {
        echo "The capital of $country is $capital<br />";
    }

?>

Output:

The capital of England is London
The capital of Scotland is Edinburgh
The capital of France is Paris

Upvotes: 5

Jay Blanchard
Jay Blanchard

Reputation: 34426

You're trying to loop through an array, $capitals, that doesn't exist. You have to loop through the array $country.

foreach ($country as $country=>$capital) {
    echo "The capital of $country is $capital";
}

Upvotes: 0

Related Questions