HTML Checkbox To PHP Array

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 "[]".

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

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

Array
(
 [option] => Array
 (
  [0] => 1
  [1] => 2
 )
 
 [submit] => Submit Query
)

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

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

This produces the array.

Array
(
 [option] => Array
 (
  [43] => 1
  [23] => 2
 )
 
 [submit] => Submit Query
)

 

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
7 + 13 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.