PHP Forms
Using Form Elements with Multiple Options
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.Solution
Example 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
Example Handling a submitted checkbox group
print 'I love ' . join(' and ', $_POST['boroughs']) . '!';
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 were checked, it’s as if you’d written the code at the top of your program.Example Code equivalent of a multiple-value form element submission
$_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="8336697">. If checked, this form element sets $_POST['population']['NY'] ['NYC'] to 8336697.
No comments:
Post a Comment