tags:

views:

67

answers:

2

What's the best way to collect data from a form using checkboxes so it's nicely grouped into one array from the $_POST array in the receiving page.

For example, in my form i'll have HTML which looks like this (x = ticked):

[x] Option One
[ ] Option Two
[x] Option Three

which i want to translated into an array from the $_POST array:

Array
(
    [a] => "Option One"
    [b] => "Option Three"
)

Is there a nice shortcut to doing this?

+6  A: 
<input type="checkbox" name="tickbox[a]" value="Option One" checked="checked">
<input type="checkbox" name="tickbox[b]" value="Option Two">
<input type="checkbox" name="tickbox[c]" value="Option Three" checked="checked">

yields

Array
(
   [a] => "Option One",
   [c] => "Option Three",
)
Ionuț G. Stan
+4  A: 

You can add square-brackets to the end of the name:

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

This will come out as

Array
(
   [0] => "Option One",
   [1] => "Option Three",
)

if the middle one isn't ticked - hopefully close enough to what you want.

Greg
Thanks, i wondered if this approach would work and intended to try it later.
Gary Willoughby