带复选框的PHP foreach循环 [英] PHP foreach loop with checkboxes

查看:89
本文介绍了带复选框的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循环?我尝试了以下方法,但没有希望

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

预先感谢

推荐答案

您的复选框名称应以[]结尾.在这种情况下,它们将自动转换为PHP中的数组.

Your checkboxes should have name with [] at the end. In this case they will automatically transform to array in 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 ['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.

这篇关于带复选框的PHP foreach循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆