Campus Module
Campus Module

Reputation: 13

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
    )

Upvotes: 0

Views: 610

Answers (2)

imran qasim
imran qasim

Reputation: 1050

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

Upvotes: 0

Arend
Arend

Reputation: 3761

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[]'/>

Upvotes: 2

Related Questions