-1

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

7
  • Are those curly quotes part of your actual code? Commented May 1, 2015 at 14:19
  • @Fred-ii- No - edited it Commented May 1, 2015 at 14:21
  • Thanks, I needed to be sure. Many actually have those as their actual quotes and we often tell them that it will throw/cause an error. Commented May 1, 2015 at 14:22
  • Have you tried Stepashka's answer below? Plus, make sure you have form tags with a POST method. Commented May 1, 2015 at 14:28
  • @Fred-ii- my form is fine, i just want to avoid using the [] at the end of the names Commented May 1, 2015 at 14:34

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

hi my names do not have square brackets at the end. How would i do it without them?
You edit your code and add them in.
@MariM i want to avoid using that method
Why do you want to avoid that @spymaster. It is the only correct way to do it.
There is a low-level way of doing it... @spymaster you can get the raw post data using this advice stackoverflow.com/questions/8945879/… 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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.