faqts : Computers : Programming : Languages : PHP : Common Problems : Forms and User Input

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

59 of 114 people (52%) answered Yes
Recently 3 of 10 people (30%) answered Yes

Entry

How do I deal with multiple checkboxes in PHP; add numeric value if box is checked?

Dec 28th, 2004 13:40
Aaron Hawley, Bryce Verdier,


The traditional method is to name each checkbox separately.  Something
like this:
<input type="checkbox" name="checkbox1" />
<input type="checkbox" name="checkbox2" />
<input type="checkbox" name="checkbox3" />
The (sloppy) PHP code would look something like this:
if (isset($checkbox1)) {
  // do something
} else if (isset($checkbox2)) {
  // do something
} else if (isset($checkbox3)) {
  // do something
}
But PHP allows arrays to be sent from HTML forms, with empty index
notation (which automagically increments pushes values to the end of the
array).
<input type="checkbox" name="checkbox[]" value="checked1" />
<input type="checkbox" name="checkbox[]" value="checked2" />
<input type="checkbox" name="checkbox[]" value="checked3" />
Then if the web user checks box the first and third checkbox you'll get
the following array in $checkbox:
array("checked1", "checked2")
Sometimes it's convenient when your checkboxes have a combined
functionality to get your checkboxed form values as an array rather than
a bunch of differently named scalar variables you need to test.