2015-05-01 67 views
0

嗨,我有一个形式PHP foreach循环使用复选框

<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> 

我有一个回答页,同时希望用户选择多个答案所以如何将我使用foreach循环的一些复选框?我试过以下,但不希望

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

在此先感谢

+0

那些卷曲的引号'''你的实际代码的一部分? –

+0

@ Fred-ii-没有 - 编辑它 – spymaster

+0

谢谢,我需要确定。许多人实际上有这些作为他们的实际报价,我们经常告诉他们,它会抛出/导致错误。 –

回答

5

你的复选框都应该在最后用[]有名字。在这种情况下,它们将自动转换为PHP中的数组。

<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代码:

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

或那样简单

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

请注意,如果用户没有选择任何复选框,$ _ POST [ '模块' ]将是未定义的。您需要在使用前先检查它。在使用之前验证用户的输入也是一种很好的做法。

+0

嗨,我的名字末尾没有方括号。没有他们我会怎么做? – spymaster

+0

您编辑您的代码并将它们添加进去。 –

+0

@MariM我想避免使用该方法 – spymaster