Zac
Zac

Reputation: 12836

Pass value of checkbox to array whether it is checked or not

I need to pass the value and a couple of other values depending on what checkboxes are checked. I found posted a couple of other times here to rely on html for this and pass a hidden value before the checkbox :

<input type="hidden" value="0"  name="B_1" />
<input type="checkbox" value="1"  name="B_1" />
<input type="hidden" value="0"  name="B_2" />
<input type="checkbox" value="1"  name="B_2" />
<input type="hidden" value="0"  name="B_3" />
<input type="checkbox" value="1"  name="B_3" />

Then in the php I am making different associations based on these checkboxes :

$b = "Buyers";
$bv1 = "Not a web item";
$bv2 = "Need sample";
$bv3 = "Sample not available";

if ($_POST['B_1']) { $b1 = array( $b , $bv1 , $_POST['B_1'] ); } 
if ($_POST['B_2']) { $b2 = array( $b , $bv2 , $_POST['B_2'] ); } 
if ($_POST['B_3']) { $b3 = array( $b , $bv3 , $_POST['B_3'] ); } 

when I use print_r I am only seeing the arrays for those boxes I checked :

Array ( [0] => Buyers [1] => Not a web item [2] => 1 )

I expect to see all of the arrays returned regardless of state of checkbox.

Array ( [0] => Buyers [1] => Not a web item [2] => 0 ) 
Array ( [0] => Buyers [1] => Need sample [2] => 1 ) 
Array ( [0] => Buyers [1] => Sample not available [2] => 0 )

Upvotes: 0

Views: 829

Answers (1)

chrisn
chrisn

Reputation: 2125

I don't see the use of your hidden fields here at all (also, they shouldn't have the same name as other elements, unless the field is an array). If you're not using them, I propose that you change your HTML to:

<input type="checkbox" value="B_1"  name="B_1" />
<input type="checkbox" value="B_2"  name="B_2" />
<input type="checkbox" value="B_3"  name="B_3" />

You can store whatever value you need in the checkbox element value attribute.

If you need all of the arrays, regardless of whether or not the boxes are checked, the if should be removed:

$b1 = array( $b , $bv1 , $_POST['B_1'] );
$b2 = array( $b , $bv2 , $_POST['B_2'] );
$b3 = array( $b , $bv3 , $_POST['B_3'] );

Upvotes: 2

Related Questions