faiz faiz - 2 months ago 11x
PHP Question

Reading dynamic checkbox array in php/html

I have multiple form fields which are created dynamically .

<label><input type="text" name="txtAmt[]">Amount</label>
<label><input type="checkbox" name="cbMarkPaid[]">Mark as Paid</label>

I use post method to submit the for to php file.I know that the checkbox won't send the data to the server when you did not check it.But i want to know the indices of the checkboxes which are not checked.

E.g. If i have 4 checkboxes cb1,cb2,cb3,cb4 and if cb3,cb4 is checked . then php recieves an array with two items :

array(2) { [0]=> string(2) "on" [1]=> string(2) "on" }

But i want the array to be as:

array(2) { [0]=> string(2) "off" [1]=> string(2) "off" [2]=> string(2) "on" [3]=> string(2) "on"}.

Please not
is also giving the same output
Thank you


You can't do this with a checkbox over POST. By definition, unchecked checkboxes are never successful.

A successful control is "valid" for submission.
All "on" checkboxes may be successful.

The best you can do is to index your array and look for the gaps. For example

<label><input type="text" name="txtAmt[0]">Amount</label>
<label><input type="checkbox" name="cbMarkPaid[0]">Mark as Paid</label>
<label><input type="text" name="txtAmt[1]">Amount</label>
<label><input type="checkbox" name="cbMarkPaid[1]">Mark as Paid</label>

Let's say you leave the first unchecked and the second checked. Then your array will look like

array(1) { [1]=> string(2) "on" }

So you know [0] was off since it wasn't submitted