tags:

views:

202

answers:

2

Hi all,

I have a form with several checkboxes. When I submit it to another php page, I am wondering: How can I tell which ones are checked without calling isset on every checkbox name? (if there is a way). If I give each of the checkboxes the same name, then only the last selected checkbox is returned.

Thanks,
Michael

+4  A: 

A quirk of PHP requires that form controls end their name with the characters [] in order for more than one of them to be recognised.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
   "http://www.w3.org/TR/html4/strict.dtd"&gt;
   <title>Demo</title>

<form action="cb.php">
<div>
    <input type="checkbox" name="animals[]" value="dog" id="dog"> 
    <label for="dog">dog</label>
</div>
<div>
    <input type="checkbox" name="animals[]" value="cat" id="cat"> 
    <label for="cat">cat</label>
</div>
<div>
    <input type="checkbox" name="animals[]" value="rabbit" id="rabbit"> 
    <label for="rabbit">rabbit</label>
</div>
<div>
    <input type="checkbox" name="animals[]" value="hampster" id="hampster"> 
    <label for="hampster">hampster</label>
</div>
<div><input type="submit"></div>
</form>
<?php
if ($_GET['animals']) {
?>
<ul>
<?php
foreach ($_GET['animals'] as $animal) {
?>
<li><?php print htmlspecialchars($animal); ?></li>
<?php
}
?>
</ul>
<?php
}
?>
David Dorward
+1  A: 

Use an array name for all the checkboxes in the same group, e.g. name="mycheckboxes[]". This way you will get an array containing the list of selected checkboxes in your php code

Zed