Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checkbox Array only showing checked values - PHP

I have a form with many checkboxes.

ex.

...
<input name="dodatkowe[]"  type="checkbox" value="1" />
<input name="dodatkowe[]"  type="checkbox" value="1" />
<input name="dodatkowe[]"  type="checkbox" value="1" />
...

I want to have all the checkboxes in the array. Array 'dodatkowe'.

When i checked all checkboxes have:

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

but when i checked example only second I have:

Array ( [0] => 1 ) 

I need that, when i check example second checkbox:

Array ( [0] => 0 [1] => 1 [2] => 0)
like image 430
Pitu Avatar asked Jan 11 '12 21:01

Pitu


2 Answers

give them indexes so you can reference them specifically...

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

Not sure why you feel you need to see the unchecked values, this can be assumed to be the inverse of the checked values.... Any attempt to do this is a hack, and is unnecessary.

like image 60
jondavidjohn Avatar answered Oct 20 '22 17:10

jondavidjohn


If a checkbox isn't checked it won't include it's value into the parameters but the first step would be to give the checkboxes a unique id:

<input name="dodatkowe[0]"  type="checkbox" value="1" />
<input name="dodatkowe[1]"  type="checkbox" value="1" />
<input name="dodatkowe[2]"  type="checkbox" value="1" />

Then you can use PHP to check is the value is there:

$maxfields = 3;
$selectboxes = $_REQUEST['dodatkowe'];
for($i = 0; $i < $maxfields; $i++)
  if(!isset($selectboxes[$i])) $selectboxes[$i] = 0;

This will set all non existent fields to 0 and $selectboxes should contain the result you are looking for.

like image 2
bardiir Avatar answered Oct 20 '22 18:10

bardiir