PHP Cookbook: Solutions and Examples for PHP Programmers
9.17.1. Problem
You have form elements that let a user select multiple choices, such as a drop-down menu or a group of checkboxes, but PHP sees only one of the submitted values. 9.17.2. Solution
End the form element's name with a pair of square brackets ([]). Example 9-28 shows a properly named group of checkboxes. Naming a checkbox group
Then, treat the submitted data as an array inside of $_GET or $_POST, as in Example 9-28. Handling a submitted checkbox group
9.17.3. Discussion
Putting [ ] at the end of the form element name tells PHP to treat the incoming data as an array instead of a scalar. When PHP sees more than one submitted value assigned to that variable, it keeps them all. If the first three boxes in Example 9-28 were checked, it's as if you'd written the code in Example 9-30 at the top of your program. Code equivalent of a multiple-value form element submission
A similar syntax also works with multidimensional arrays. For example, you can have a checkbox such as <input type="checkbox" name="population[NY][NYC]" value="8008278">. If checked, this form element sets $_POST['population']['NY']['NYC'] to 8008278. 9.17.4. See Also
The introduction to Chapter 4 for more on arrays. |
Категории