Kodi



Showing posts with label php associative array exercise. Show all posts
Showing posts with label php associative array exercise. Show all posts

Tuesday, December 25, 2018

PHP associative array exercise

A list of countries as well as cities:

Tokyo, Japan; Mexico City, Mexico; New York City, USA; Mumbai, India; Seoul, Korea; Shanghai, China; Lagos, Nigeria; Buenos Aires, Argentina; Cairo, Egypt; London, England.

Create an associative array, using the countries as keys, the cities as values. Create a form for the user, with the instructions Please choose a city:

Follow this request with a select field for the 10 cities, with the options created by looping through the array. When the user clicks the submit button, return the statement $city is in $country., where $city is the value chosen by the user, and $country is its key.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
   
     <html xmlns="http://www.w3.org/1999/xhtml"  xml:lang="en" lang="en">
     <head>
     <meta http-equiv="content-type" content="text/html;charset=iso-8859-1" />
     <title>Associative Array - Cities</title>
     </head>
   
     <body>
     <h2>Large Cities Again<br /></h2>
   
     <?php
     //Create associative array with countries as keys, cities as values.
$cities=array (
    "Japan" => "Tokyo",
    "Mexico" => "Mexico City",
    "USA" => "New York City",
    "India" => "Mumbai",
    "Korea" => "Seoul",
    "China" => "Shanghai",
    "Nigeria" => "Lagos",
    "Argentina" => "Buenos Aires",
    "Egypt" => "Cairo",
    "UK" => "London"
    );
//If form not submitted, display form.
if(!isset($_POST['submit'])){
    ?>

<form method="post" action="#">
<p>Please choose a city:</p>
<select name="city">

<?php
  //Use array to create options for select field.
  //Be sure to escape the quotes and include a line feed.
  foreach($cities as $c){
    echo "<option value=\"$c\">$c</option>\n";
  }
?>

</select> <p />
<input type="submit" name="submit" value="Go">
</form>

<?php
  //If form submitted, process input.
  }else{
    //Retrieve user response.
    $city=$_POST['city'];
    //Find corresponding key in associative array.
    $country=array_search($city, $cities);
    //Send the data back to the user.
    echo "<p>$city is in $country.</p>" ;

  }
?>

</body>
</html>
   


Ads

Featured Post

SAS.Team SAS SAS.Planet.bin

SAS.Planet.bin for windows - all versions multilingual SAS . Planet SAS.Planet Screenshot of SAS.Planet. Author: SASGIS. Platform:...

Popular

Ads