PHP: Checkbox Array in Form Handling – Multiple Checkbox Values in an Array

by Yang Yang on January 31, 2009

Checkboxes is probably one of the most frequently used form controls which come handy in dealing with one to many relationships.

The multiple selective nature of HTML form checkboxes require a convenient way for PHP to process multiple checkbox values, ideally in a single array.

By default, each and every HTML input control including checkboxes posts its value to server-side PHP script by a unique identity that is specified by attribute name=”variable-A”. This approach is generally fine with simple pairs of name and value. However, with multiple checkboxes in the form and probably a lot of them, you will need to assign every single one of them a different name which is quite bitsy and not neat at all.

The solution is for PHP to identify the entire series of checkboxes as a single array accessible via a common index in $_POST. This is achievable by simply inserting the array index operator ‘[]’ to the name attribute of the checkbox control:

<input type="checkbox" name="tags[]" value="1" />
<input type="checkbox" name="tags[]" value="2" />
<input type="checkbox" name="tags[]" value="3" />
<input type="checkbox" name="tags[]" value="4" />

This way, the PHP script processing POST will figure it out automatically and treat $_POST[‘tags’] as an array containing the values 1, 2, 3 and 4:

// output
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4

Now much more handy, huh!