0

Hi i have a number of checkboxes in a form

<p>Select the modules you take:<br/>
Business <input type="checkbox" name="modules" value="Business"/><br />
Accounting <input type="checkbox" name="modules" value="Accounting"/><br />
Marketing <input type="checkbox" name="modules" value="Marketing" /><br />
</p>

I have a response page and expect the user to choose multiple answers so how would i use a foreach loop? I've tried the following but no hope

foreach($modules as $selected){
print "The modules were ".$modules;
}

Thanks in advance

spymaster
  • 25
  • 1
  • 4

1 Answers1

6

Your checkboxes should have name with [] at the end. In this case they will automatically transform to array in PHP.

i.e.

<p>Select the modules you take:<br/>
Business <input type="checkbox" name="modules[]" value="Business"/><br />
Accounting <input type="checkbox" name="modules[]" value="Accounting"/><br />
Marketing <input type="checkbox" name="modules[]" value="Marketing" /><br />
</p>

php code:

echo "The modules were: "
foreach($_POST['modules'] as $selected) {
    echo $modules." ";
}

or as simple as

echo "The modules were: ".implode(", ", $_POST['modules']).".";

Please note that if user doesn't select any checkbox $_POST['modules'] will be undefined. You need to check it first before use. it is also a good practice to validate user's input before usage.

Stepashka
  • 2,648
  • 20
  • 23
  • hi my names do not have square brackets at the end. How would i do it without them? – spymaster May 01 '15 at 14:31
  • You edit your code and add them in. – Muhammad Abdul-Rahim May 01 '15 at 14:33
  • @MariM i want to avoid using that method – spymaster May 01 '15 at 14:33
  • Why do you want to avoid that @spymaster. It is the only *correct* way to do it. – Jay Blanchard May 01 '15 at 14:47
  • 1
    There is a low-level way of doing it... @spymaster you can get the raw post data using this advice http://stackoverflow.com/questions/8945879/how-to-get-body-of-a-post-in-php and parse it manually. Dat will contain something like '... &modules=Business&modules=Accounting& ...' But I do not see any reason why anybody want to do it in this simple case. – Stepashka May 01 '15 at 14:54