Arrays with Numeric Indexes

 

Introduction.  The last webpage gave some general background about arrays that was hopefully pretty much a review for you.  Now we want to work an example that initializes an array from a user's inputs on a form.

You should call the form page test_scores.html.  We have configured it so it only has text boxes for four test scores.

 

<html>
<head>
<title>Compute Averages</title>
</head>

<body bgcolor = "660000" text="cccccc">
<form action="average_test_scores.php" method=post>
<table align = center>
<tr>
<td><font size = 4 color=cccccc>Test 1:</font>
</td>
<td><input type=text name="txtTest1" size=6>
</td>
</tr>
<tr>
<td><font size = 4 color=cccccc>Test 2:</font>
</td>
<td><input type=text name="txtTest2" size=6>
</td>
</tr>
<tr>
<td><font size = 4 color=cccccc>Test 3:</font>
</td>
<td><input type=text name="txtTest3" size=6>
</td>
</tr>
<tr>
<td><font size = 4 color=cccccc>Test 4:</font>
</td>
<td><input type=text name="txtTest4" size=6>
</td>
</tr>
<tr>
<td colspan = 2 align = center><input type = submit name="submit" value="compute average">
</td>
</tr>
</table>
</form>
</body>
</html>

 

The script to process the user inputs does not assume that all four text boxes have entries.  We do some processing so that the computations do not include blank entries.

You should call the processing script average_test_scores.php.

 

<html>
<head>
<title>Computing the Average</title>
</head>

<body>
<?php
// obtaining the information from the form
// and placing them in an array

$grades = array( );
$grades[] = $txtTest1;
$grades[] = $txtTest2;
$grades[] = $txtTest3;
$grades[] = $txtTest4;
// initializing a counter for the non-blank entries
$nonblank_entries = 0;
// looping through the array to average the existing entries
for ($n = 0; $n < count($grades); $n++)
{

// displaying the elements of the array
print "element grades[<b>$n</b>] = <b>$grades[$n] </b><BR>\n";
if ($grades[$n] != "")
{

$nonblank_entries++;
$average = $average + $grades[$n];

}

}
$average = $average/$nonblank_entries;
print "<BR><BR><font size = 4>The average of $nonblank_entries non-blank entries is = <b>$average</b></font>";
?>
</body>
</html>

 

Notice that we have an if (condition) nested within our loop.