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.
This Post Has 9 Comments
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
Haha. Thanks! Fixed
Thanks!
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?
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].
What do you mean by 2nd level array? Is not it simply an associative array?
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.
Thanks a lot sir John!
This article that you’ve made really solve an important problem in my project.
Thanks a lot!
God Bless ya sir!
No problem!