Checkbox Array only shows 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 an array. Array of 'dodatkowe'.

When I checked all the checkboxes, follow these steps:

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

but when I checked the example is only the second, I have:

 Array ( [0] => 1 ) 

I need this when I check the second box:

 Array ( [0] => 0 [1] => 1 [2] => 0) 
+4
source share
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 that you need to see unverified values, this can be considered inverted for the marked values ​​.... Any attempt to make this hack is not necessary.

+3
source

If the checkbox is not selected, it will not include its value in the parameters, but the first step is to assign a unique identifier to the flags:

 <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 if there is a value:

 $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.

+2
source

Source: https://habr.com/ru/post/1390527/


All Articles