Several Checkboxes sharing the same name

Buzu picture Buzu · May 14, 2013 · Viewed 28.7k times · Source

According to the w3c "Several checkboxes in a form may share the same control name. Thus, for example, checkboxes allow users to select several values for the same property." However, if you do that, PHP will only take the last value. For example:

<?php
if ($_POST) {
echo "<pre>";
print_R($_POST);
echo "</pre>";
}
?>
<form action="" method = "post">
<input type="checkbox" name="pet" value="dog" />Dog<br />
<input type="checkbox" name="pet" value="Cat" />Cat<br />
<input type="checkbox" name="pet" value="bird" />bird<br />
<input type="checkbox" name="pet" value="iguana" />iguana<br />
<input type="submit" />
</form>

If you submit that form, you will see that only the checked box that appears last will be set. The browser sends them all, but they overwrite each other. So, setting the same name to several checkboxes can cause problems. Has it always been like that? I seem to remember that it was possible to actually send all the values as an array.

I know that you can just add an [] at the end of the name to create an array of values:

<?php
if ($_POST) {
echo "<pre>";
print_R($_POST);
echo "</pre>";
}
?>
<form action="" method = "post">
<input type="checkbox" name="pet[]" value="dog" />Dog<br />
<input type="checkbox" name="pet[]" value="Cat" />Cat<br />
<input type="checkbox" name="pet[]" value="bird" />bird<br />
<input type="checkbox" name="pet[]" value="iguana" />iguana<br />
<input type="submit" />
</form>

But the w3c doesn't specify that. Honestly I don't remember if I always used the [] at the end of the name, but for some reason I think at some point I didn't. Was there any time in the past when you could make it work without the []?

http://www.w3.org/TR/html401/interact/forms.html#checkbox

Answer

sourcejedi picture sourcejedi · May 14, 2013

That would never have worked without the [], not in PHP.

W3C don't specify anything about how query strings are handled server-side. (Ignoring an irrelevant, obsolete corner of the CGI spec, only relevant to PHP in that it was a security hole up until recently).

It looks like that pattern is valid markup, but not commonly used, for the reason you describe.

A similar pattern is used for radio buttons, of which only one can be selected at a time. (In fact, giving the radio inputs the same name is how the browser knows to treat them as a group). Perhaps that's what you were thinking of.