PHP form data into array
During PHP form processing it often occurs that the visitor can select multiple answers. It is in the case of checkboxes, list- and combo boxes. Let's suppose the following HTML form element:
<select name="color" size=3 multiple>
<option>Red</option>
<option>Green</option>
<option>Blue</option>
<option>Black</option>
<option>White</option>
</select>
In this example, the visitor can select more colors at once. This is the result of the multiple
parameters inside the select
tag.
If you check the $_POST
superglobal you will find all form variables in it. However, if you check it more precisely you will find that the color variable contains only one of your selections. Where are the other selected values? Yes, they are missing in this case.
To solve this problem it would be nice if we would get an array with all of the user selection. Fortunately, it is a quite simple task. You just need to edit the name
parameter in your HTML form and add a []
after it as follows:
<select name="color[]" size=3 multiple>
<option>Red</option>
<option>Green</option>
<option>Blue</option>
<option>Black</option>
<option>White</option>
</select>
Using this code you will get an array named color inside the $_POST
array and this internal array contains all of the user-selected values.
That's all.