dmubu
dmubu

Reputation: 33

How to return PHP array value from key?

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.

Upvotes: 3

Views: 24173

Answers (2)

user562854
user562854

Reputation:

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

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

Upvotes: 1

Spyros
Spyros

Reputation: 48626

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];

Upvotes: 9

Related Questions