Recipe 9.17. Using Form Elements with Multiple Options


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

<input type="checkbox" name="boroughs[]" value="bronx"> The Bronx <input type="checkbox" name="boroughs[]" value="brooklyn"> Brooklyn <input type="checkbox" name="boroughs[]" value="manhattan"> Manhattan <input type="checkbox" name="boroughs[]" value="queens"> Queens <input type="checkbox" name="boroughs[]" value="statenisland"> Staten Island

Then, treat the submitted data as an array inside of $_GET or $_POST, as in Example 9-28.

Handling a submitted checkbox group

<?php print 'I love ' . join(' and ', $_POST['boroughs']) . '!'; ?>

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

<?php $_POST['boroughs'][] = "bronx"; $_POST['boroughs'][] = "brooklyn"; $_POST['boroughs'][] = "manhattan"; ?>

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.




PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net