简体   繁体   English

如何在PHP中获取多个复选框值

[英]How to get multiple checkbox values in PHP

I have following code of five checkboxes with similar name=check[] 我有以下五个带有类似name=check[]复选框的代码

<input type='checkbox' value='1' name='check[]'/>
<input type='checkbox' value='1' name='check[]'/>
<input type='checkbox' value='1' name='check[]'/>
<input type='checkbox' value='1' name='check[]'/>
<input type='checkbox' value='1' name='check[]'/>

I am sending this data to PHP page using form and extracting this data in php as following 我使用表单将数据发送到PHP页面,并按照以下步骤在php中提取数据

<?php
$check=$_POST['check'];
print_r($check);
?>

Output for three checked checkboxes will always be as following even If i check checkbox no 1,2,5 or 1,3,4 即使我未选中1,2,5或1,3,4复选框,三个已选中复选框的输出也始终如下

Array
(
    [0] => 1
    [1] => 1
    [2] => 1
)

For Example: 例如:

If there are total five checkboxes and i only checked 1st and 3rd checkbox then my output must be 如果总共有五个复选框,而我只选中了第一和第三复选框,那么我的输出必须是

Array
(
    [1] => 1
    [3] => 1
)

or 要么

Array
    (
        [1] => 1
        [2] => 0
        [3] => 1
        [4] => 0
        [5] => 0
    )

The browser will send the values of the checked checkboxes, right now your values are always 1. 浏览器将发送选中的复选框的值,现在您的值始终为1。

Try changing your code to: 尝试将代码更改为:

<input type='checkbox' value='1' name='check[]'/>
<input type='checkbox' value='2' name='check[]'/>
<input type='checkbox' value='3' name='check[]'/>
<input type='checkbox' value='4' name='check[]'/>
<input type='checkbox' value='5' name='check[]'/>

get all the values from the checkboxes like you are doing, than do a for loop untill the length of array and if particular value of any key is 1 than you can do process on it as you like for example 像执行操作一样从复选框中获取所有值,然后执行for循环直到数组的长度,并且如果任何键的特定值是1,那么您就可以根据需要对其进行处理,例如

 $data = array(
    [1] => 1
    [2] => 0
    [3] => 1
    [4] => 0
    [5] => 0
);
 $output=array();
 for($i=1; $i<=count($data); $i++)
 {
    if($data[$i])== 1)
      $output[] = $data[$i];
 }
 print_r($output);

i hope this will solve your problem. 我希望这能解决您的问题。

Regards 问候

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM