php php中的foreach复选框POST

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14543050/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 07:29:22  来源:igfitidea点击:

foreach checkbox POST in php

phppostcheckbox

提问by Curtis Crewe

Basically my question is the following, how can i select on "Checked" checkbox's while doing a $_POST request in PHP, currently i have the checkbox's doing an array as shown below.

基本上我的问题如下,如何在 PHP 中执行 $_POST 请求时选择“已检查”复选框,目前我有复选框正在执行如下所示的数组。

<input type="checkbox" value="1" name="checkbox[]">
<input type="checkbox" value="2" name="checkbox[]">
<input type="checkbox" value="2" name="checkbox[]">
<input type="checkbox" value="3" name="checkbox[]">

I want to be able to do something like this

我希望能够做这样的事情

foreach(CHECKED CHECKBOX as CHECKBOX) {
   echo CHECKBOX VALUE;
}

I've tried doing similar to that and it's not echoing anything.

我试过做类似的事情,但它没有回应任何东西。

回答by ThiefMaster

foreach($_POST['checkbox'] as $value) {

}

Note that $_POST['checkbox']will onlyexist if at least one checkbox is checked. So you mustadd an isset($_POST['checkbox'])check before that loop. The easiest way would be like this:

请注意,只有在至少选中一个复选框$_POST['checkbox']才会存在。因此,您必须isset($_POST['checkbox'])在该循环之前添加检查。最简单的方法是这样的:

$checkboxes = isset($_POST['checkbox']) ? $_POST['checkbox'] : array();
foreach($checkboxes as $value) {
    // here you can use $value
}

回答by Timur

This type of questions can be easily understood printing $_POST: var_dump($_POST);. You'll see that PHP receive values of checked checkboxes in numeric array.

这种类型的问题可以很容易理解打印$_POSTvar_dump($_POST);。您将看到 PHP 接收数值数组中选中复选框的值。

foreach ( $_POST['checkbox'] as $value ) {
    echo $value;
}