Associative Arrays

 

Introduction.  Now that we have discussed arrays that have numeric indexes we need to spend some time looking at arrays that use indexes that are strings.  These are often called associative arrays.

We are going to use a select box to list the names of some universities.  A user should select one of the schools and press the button.  The URL for the school will be displayed on another page.  You should call the form page find_url.html.

 

<html>
<head>
<title>Find the URL</title>
</head>

<body bgcolor = "660066" text="cccccc">
<form action="find_url.php" method=post>
<table align = center>
<tr>
<td><font size = 4 color=cccccc>Please select a school from the following list</font>
</td>
</tr>
<tr>
<td align = center><font size = 4 color=cccccc>
<select name="school_name">
<option>Michigan State</option>
<option>Purdue</option>
<option>Quinnipiac</option>
<option>Rider</option>
<option>Syracuse</option>
<option>University Tennessee</option>
<option>Virginia Tech</option>
</select>
</td>
</tr>
<tr>
<td colspan = 2 align = center><input type = submit value="Find the URL">
</td>
</tr>
</table>
</form>
</body>
</html>

 

You should call the processing script find_url.php.

 

<html>
<head>
<title>Finding a URL</title>
</head>

<body>
<?php
// initializing the array of URLs
// based on entry names

$urls = array(
"Michigan State" => "msu.edu",
"Purdue" => "purdue.edu",
"Quinnipiac" => "quinnipiac.edu",
"Rider" => "rider.edu",
"Syracuse" => "syracuse.edu",
"University Tennessee" => "utk.edu",
"Virginia Tech" => "vt.edu"
);
// displaying the URL bassed on finding the entry in the array
print "<center><h2>The URL for <b>$school_name</b> is = <b>$urls[$school_name]</b></h2></center>";
?>
</body>
</html>

 

Remember $school_name is determined by the value posted from the form control called school_name.