Close

php forms

PHP Multiple Checkbox Array Handling

Handling Checkboxes in PHP Forms

I tend to get a lot of questions around checkbox handling when submitting forms to  PHP. Here’s a simple snippet to illustrate how it works:

<?php
print_r($_POST);
?>
<form method="post">
Car <input type="checkbox" name="stuff[car]" value="1" />
Dog <input type="checkbox" name="stuff[dog]" value="1" />
<input type="submit" value="Submit" />
</form>

A couple things to pay attention to here…

1. Notice the input names. They follow this pattern name[key]. The name is really the name of the “group” of checkboxes. The key is the name of that individual checkbox. This is how you know which checkboxes were checked and which weren’t. When submitted, this form will only include the checkboxes that ARE checked.

2. Notice the created array. When this form is submitted the output will look something like this:

Array ( [stuff] => Array ( [car] => 1 [dog] => 1 ) )

If you look at our inputs… “stuff” becomes the top-level array key, “dog” and “car” become the 2nd-level array keys, and the input values become the values of “dog” and “car” respectively.

With this, you can properly handle these checkboxes and process them accordingly.

December 31, 2013