Snipe.Net Geeky, sweary things.

Checkboxes/Multiple Select Boxes in PHP

C

For the PHP newbie, checkboxes and/or multiple select listboxes can be baffling in the beginning. It’s actually not very hard at all, and is often one of the PHP newbie’s first experience with arrays.

The logic behind checkboxes and multiple select listboxes is identical. Because of this, we’ll get the HTML bit of it done for both:

A. Checkboxes
<input type=”checkbox” name=”foo[]” value=”1″>
<input type=”checkbox” name=”foo[]” value=”2″>
<input type=”checkbox” name=”foo[]” value=”3″>
(etc….)

B. Multiple Select Listboxes
<select name=”foo[]” size=”4″ multiple>
<option value=”apples”>Apples</option>
<option value=”oranges”>Oranges</option>
<option value=”pears”>Pears</option>
<option value=”grapes”>Grapes</option>
<option value=”mangos”>Mangos</option>
</select>

Getting the data out

Now we just have to write the PHP code that will be able to extract the data the user selected from the array we created ($foo[])

[sourcecode language=’php’] // check to be sure at least one option was selected
$foo = $_POST[‘foo’];
if (count($foo) > 0) {
// loop through the array
for ($i=0;$i$foo[$i] \n”;

} // end “for” loop

} // endif[/sourcecode]

About the author

snipe

I'm a tech nerd from NY/CA now living in Lisbon, Portugal. I run Grokability, Inc, and run several open source projects, including Snipe-IT Asset Management. Tweet at me @snipeyhead, skeet me at @snipe.lol, or read more...

By snipe
Snipe.Net Geeky, sweary things.

About Me

I'm a tech nerd from NY/CA now living in Lisbon, Portugal. I run Grokability, Inc, and run several open source projects, including Snipe-IT Asset Management. Tweet at me @snipeyhead, skeet me at @snipe.lol, or read more...

Get in Touch