简体   繁体   中英

How to get multiple checkbox values in PHP

I have following code of five checkboxes with similar 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
$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

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.

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

 $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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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