How to return PHP array value from key?
22,532
Solution 1
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];
Solution 2
...
<?php
$city = $_POST["city"];
print ("$city is in ".$cities[$city]);
?>
Author by
Admin
Updated on July 31, 2020Comments
-
Admin almost 4 years
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.