PHP foreach循环与复选框

spy*_*ter 0 php foreach loops

嗨,我在表单中有许多复选框

<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>
Run Code Online (Sandbox Code Playgroud)

我有一个响应页面,期望用户选择多个答案,那么我将如何使用foreach循环?我尝试过以下但没有希望

foreach($modules as $selected){
print "The modules were ".$modules;
}
Run Code Online (Sandbox Code Playgroud)

提前致谢

Ste*_*hka 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>
Run Code Online (Sandbox Code Playgroud)

php代码:

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

或者如此简单

echo "The modules were: ".implode(", ", $_POST['modules']).".";
Run Code Online (Sandbox Code Playgroud)

请注意,如果用户未选中任何复选框,则$ _POST ['modules']将是未定义的.您需要在使用前先检查它.在使用之前验证用户的输入也是一种很好的做法.