Helping ordinary people create extraordinary websites!

Using HTML Forms With PHP

By Nicholas Chase
2004-01-09

One Name, Multiple Values
So far, each name has corresponded to only one value. What happens when there's more than one value? The crew species list box, for example, allows multiple values to be submitted with the name crew.

Ideally, you'd like these values to be available as an array so you can retrieve them explicitly. To make that happen, you've got to make a slight change to the HTML page. Fields that are to be submitted as arrays should be named with brackets, as in crew[]:

Listing 4. Modifying the HTML page


...
<td>
<select name="crew[]"

multiple="multiple">
<option value="xebrax">Xebrax</option>

<option value="snertal">Snertal</option>
<option value="gosny">Gosny</option>#
</select>
</td>
...


Once you've made this change, retrieving the form value actually yields an array:

Listing 5. Accessing the variables as an array


...
$crew_values = $HTTP_GET_VARS

['crew'];
echo "0) ".$crew_values[0];
echo "<br />";
echo "1) ".$crew_values[1];
echo "<br />";
echo "2) ".$crew_values[2];

...


Submitting the page now shows the multiple values:


0) snertal
1) gosny
2)

Notice first that this is a zero-based array. The first value encountered is in position 0, the next in position 1, and so on. In this case, I submitted only two values, so the third spot is blank.

Normally, you don't know how many items will be submitted, so instead of calling each item directly you can use the fact that it's an array to your advantage, using the sizeof() function to determine how many values were submitted:

Listing 6. Determining the size of the array
...

for ($i = 0; $i < sizeof($crew_values); $i++) {

echo $crew_values[$i];
echo "<br />";
}
...


Sometimes, however, the problem is not too many values, but no values at all.



Tutorial pages:

First published by IBM developerWorks


 2 Votes

You might also want to check these out:


Leave a Comment on "Using HTML Forms With PHP"
You must be logged in to post a comment.

Link to This Tutorial Page!


GET OUR NEWSLETTERS