Close

December 31, 2013

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:

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.

7 Comments on “PHP Multiple Checkbox Array Handling

Peter J Langley
January 2, 2014 at 11:42 am

Hello – thanks for your article =)

FYI – the input field labels don’t correctly correspond to the input name attributes (Dog is stuff[car]):
Dog
Car

Reply
John Morris
January 2, 2014 at 12:07 pm

Haha. Thanks! Fixed

Reply
James Franklin
April 22, 2014 at 12:45 pm

Thanks!

Reply
Martin Kirk
June 5, 2014 at 5:36 pm

Hi John,

is there any reason you choose this method over the following:

Car
Dog

which results in the array:

[stuff] => Array
(
[0] => Car
[1] => Dog
)

just curious if it’s a matter of preference or if there are advantages to one method or the other?

Reply
John Morris
June 8, 2014 at 8:02 am

Yes actually. Having keys of 0, 1, 2, etc… don’t provide any meaning. If we were to look at it, we wouldn’t know what stuf[0] really means. But, stuff[car] would have some meaning built into it… and then we’d know the state to be 0 or 1… which is checked or unchecked. Technically, you could do it the other way… but it’s standard practice to do stuff[car] instead of stuff[0].

Reply
ناصر الدین عامر
January 4, 2015 at 6:43 am

What do you mean by 2nd level array? Is not it simply an associative array?

Reply
todd
February 26, 2015 at 12:22 pm

Thanks a ton for your excellent tutelage, what fantastic help! Funny, was just watching your ‘php in 30 min’, needing this info-and there u are.

Reply

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.