HTML Checkbox To PHP Array

3rd April 2008

To create a simple HTML check box use the following bit of code.

<input type="checkbox" name="option2" value="Milk" />

To set the checkbox as filled in include a checked attribute. To make the control XHTML compliant you will need to do the following.

<input type="checkbox" name="option2" value="Milk" checked="checked" />

When the form is posted this value is sent to PHP with the $_POST superglobal array.

To link several checkboxes together to make them into an array in the PHP $_POST array you need to make all of the checkboxes have the same name, and each name must end in "[]".

  1. <input type="checkbox" name="option[]" value="1" />
  2. <input type="checkbox" name="option[]" value="2" />

When both of the checkboxes are filled and the form is submitted this produces the following array.

  1. Array
  2. (
  3. [option] => Array
  4. (
  5. [0] => 1
  6. [1] => 2
  7. )
  8.  
  9. [submit] => Submit Query
  10. )

To set values in the array you can include a string in between the [] in the checkbox name.

  1. <input type="checkbox" name="option[43]" value="1" />
  2. <input type="checkbox" name="option[23]" value="2" />

This produces the array.

  1. Array
  2. (
  3. [option] => Array
  4. (
  5. [43] => 1
  6. [23] => 2
  7. )
  8.  
  9. [submit] => Submit Query
  10. )

 

Add new comment

The content of this field is kept private and will not be shown publicly.