-2

Im trying to get all of the checked values using array i already get all of the checked box and get the value but my problem is i want to pass to array all of value of checbox, 1 for check and 0 for uncheck. sorry for the english.

this is what i want to get:

array[0] = 1 //check
array[1] = 0 // uncheck 
// and so on.

i have already tried a hidden box with same name of checkbox but it give me wrong data of array and i am sure its not the answer

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


$checkbox1 = ($_POST['checkbox'] <> 0) ? ($_POST['checkbox']) : (empty($_POST['checkbox'])) ?'0'    : '';

output: 0

output of print_r($checkbox1) : 0

expected output : array[0]=> 1 --> check array[1] => 0 -> uncheck

Regolith
  • 2,944
  • 9
  • 33
  • 50
Kitz Suizo
  • 11
  • 1
  • 2
    Possible duplicate of [Do checkbox inputs only post data if they're checked?](https://stackoverflow.com/questions/11424037/do-checkbox-inputs-only-post-data-if-theyre-checked) – Alex Barker Sep 04 '19 at 01:54
  • i already seen that bro but the answer its get is throug hidden textbox – Kitz Suizo Sep 04 '19 at 01:55
  • 2
    Hi, sorry I have flagged your question as a duplicate. I believe the answer [here](https://stackoverflow.com/questions/11424037/do-checkbox-inputs-only-post-data-if-theyre-checked) outlines that this behavior is part of the specification, which is why all of the answers you have found involve a hidden input. If you use a radio button, you can achieve the desired result, almost. – Alex Barker Sep 04 '19 at 01:56

1 Answers1

1

When working with a PHP backend where you want to post an array of values (using the name="something[]" syntax) you need to create <input type="hidden"> and <input type="checkbox"> pairs that will refer to the exact same array index.

You do so by explicitly defining the index in the name attribute.

For example

<input type="hidden" name="checkbox[0]" value="0">
<input type="checkbox" name="checkbox[0]" value="1">

<input type="hidden" name="checkbox[1]" value="0">
<input type="checkbox" name="checkbox[1]" value="1">

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

I believe this also works for ASP.NET-MVC backends. Not sure about others though.


If you're looping over records or a range, this is as simple as keeping an iteration index and using it in the name attributes

<?php for ($i = 0; $i < $range; $i++): ?>
  <input type="hidden" name="checkbox[<?= $i ?>]" value="0">
  <input type="checkbox" name="checkbox[<?= $i ?>]" value="1">
<?php endfor ?>
Phil
  • 157,677
  • 23
  • 242
  • 245