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 []?
[]
and then you can usein_array
to determine which checkboxes have been selected. Annoying, but aren't all forms? – Lovellalovelockphp
specific (and possibly other languages) and not related to the w3c. Other languages do not have this requirement. As you stated, the browser does send all values. – Kite