PHP Tips building web forms

Sometimes when building web forms, you may need to collect multiple values for a single field. Perhaps you have a form which gives a list of common hobbies, and visitors can check all hobbies which interest them. But how do you get PHP to realize that the user has made multiple selections? All you need to do is append square brackets to the end of the field name in your HTML.

For example,

<input type=”checkbox” name=”hobbies[]” value=”Computers”>Computers
<input type=”checkbox” name=”hobbies[]” value=”Fishing”>Fishing
<input type=”checkbox” name=”hobbies[]” value=”Hiking”>Hiking

If a visitor selects all three checkboxes, when the form is posted, your script will have an array named $_POST[hobbies] which contains the three hobbies as its elements.

Comments are closed.