AKor
AKor

Reputation: 8882

Handling a dynamic amount of checkboxes with PHP

I'm making a form that requires me to use a varying amount of checkboxes. Anywhere from 0 to n. I can easily insert the value I want into the value="" of the checkbox, so that's not a problem.

My question is - how would I write a PHP form that can take any amount of checkbox values from 1 to n, and then loop through all of those values?

Upvotes: 0

Views: 2581

Answers (3)

Chris McClellan
Chris McClellan

Reputation: 1105

I would do this for your HTML

<input type="checkbox" name="checkbox[]" value="your_supplied_value1"  />
<input type="checkbox" name="checkbox[]" value="your_supplied_value2"  />

if (isset($_POST['checkbox'])) {
  foreach ($_POST['checkbox'] as $c) {
    // do something 
  }
}

Upvotes: 5

Jase
Jase

Reputation: 599

use the array type for the name

name="name[]"

This passes an array to $_POST['name'] which you can foreach through

Upvotes: 1

teuneboon
teuneboon

Reputation: 4064

Something like this:

<?php
for($i = 0; $i < $n; $i++) {
    ?><input type="checkbox" name="checkthisbox[<?=$i?>]" value="value" /> checkbox :)<?php
}
?>

then loop through them like this:

<?php
foreach ($_POST['checkthisbox'] as $checkbox) {
    var_dump($checkbox);
}
?>

untested, but something like this should work

Upvotes: -1

Related Questions