To demonstrate some of the things you can do with arrays, I made an array of country codes and country names. I put it in a file by itself so I can use it in several other pages using include(). The array I'll use is $country_code and is located in country_codes.php. You can see the source code on country_codes_c.php. As you can see, it is an associative array of country names indexed by their country codes.
If you are adding members to an array and taking them away you can loose track of how many members are in the array. To find out how many there are you can use count(). After I made the array $country_code, I wondered how many countries were in it. Instead of counting them, I included the file with it in the top of this page:
<?
include("arrays/country_codes.php");
?>
Now that $country_code is on this page, I can use count() to tell me how many countries are in the list:
<?
$num = count($country_code);
echo "There are 0 countries in the array.";
?>
There are 249 countries in the array.
foreach() is a way to loop through an array executing a block of code for each member. The syntax is
<?
foreach ( $array as $index=>$member )
{
/* code block to be executed */
}
?>
$array is the array you are working on. $index and $member are temporary holders for the index/member pair foreach() is working with. The following code uses foreach() to output $country_code in the table on this page:
<? include("country_codes.php"); ?>
<html>
<body>
<center>
<table border="5">
<tr>
<th>Code</th>
<th>Country</th>
</tr>
<?
foreach ( $country_code as $code=>$country )
{
echo "<tr>";
echo "<td align=\"center\">$code</td>";
echo "<td>$country</td>";
echo "</tr>";
}
?>
</table>
</center>
</body>
</html>
For my example of radio buttons, I have a list of colors to make the background color of a table. For that example, I only show the source code for the HTML. Here, I will show you the PHP behind the form.
PHP does two things in this script; create the table and process the form input. To make the table, I first make an array of the colors I'll use
$colors = array(aaaaff, aaffaa, aaffff, ffaaaa, ffaaff, ffffaa);
then use foreach to loop through the array creating the table row for each color in the array. If I later add a color, I don't have to make a new <tr> for that color, the foreach loop does it for me. The <table> tag includes an if statement that checks to see if a color has been submitted to the form and if there has been add a background color to the <table> tag.
<form>
<center>
<table border="1"<?
if ( isset($_GET[form_bg]) )
{ echo " bgcolor=\"#$_GET[form_bg]\"";}
echo ">";
$colors = array(aaaaff, aaffaa, aaffff, ffaaaa, ffaaff, ffffaa);
foreach( $colors as $temp )
{ echo "<tr>
<td bgcolor=\"#$temp\" width=\"20\"><input type=\"radio\" name=\"form_bg\" value=\"$temp\"></td>
<td>#$temp</td>
</tr>"; }
?>
<tr>
<td align="center" colspan="2"><input type="submit"></td>
</tr>
</table>
</center>
</form>
|
|
|