3

I am trying to generate a user's country based on the city selection in a select menu. I have generated the select menu using an associative array. I want to print "$city is in $country" but I cannot access the $country properly. This is what I have:

<?php
$cities = array("Tokyo" => "Japan", "Mexico City" => "Mexico", 
"New York City" => "USA", "Mumbai" => "India", "Seoul" => "Korea",
"Shanghai" => "China", "Lagos" => "Nigeria", "Buenos Aires" => "Argentina", 
"Cairo" => "Egypt", "London" => "England");
?>

<form method="post" action="5.php">
<?php
echo '<select name="city">';

foreach ($cities as $city => $country)
{
echo '<option value="' . $city . '">' . $city . '</option>';
}

echo '<select>';

?>

<input type="submit" name="submit" value="go" />
</form>
<?php
$city = $_POST["city"];

print ("$city is in $country");
?>

Any ideas? Thank you.

2 Answers 2

8

You are trying to access the local foreach variable $country out of the foreach loop. You have to do that inside the loop.

Or you could just get the country from the cities array like :

$cities[$city];
Sign up to request clarification or add additional context in comments.

Comments

1
...
<?php
$city = $_POST["city"];

print ("$city is in ".$cities[$city]);
?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.