Jump to content

How to populate array values from a single checkbox?


benphp

Recommended Posts

I have a grid, where there is a single checkbox will indicate a yes/no value:

 

Field1 | Field 2
   x   |
   x   |   x

etc.

 

And I'm using an array for each field on each row:

 

<input type=\"checkbox\" name=\"Field1[]\" value=\"$Field1\" />
<input type=\"checkbox\" name=\"Field2[]\" value=\"$Field2\" />

 

The problem: When I cycle through the array, it only contains values for checked boxes - and doesn't contain a value for unchecked boxes. So if my table has 20 rows and 5 are checked, I only get an array with 5 elements.

 

A table with 20 rows, 5 checked:

foreach ($_POST['Field1'] as $f1) {
print "F = $f1 <br />";
}

 

Results:

 

F = 1

F = 1

F = 1

F = 1

F = 1

 

I would expect to get "F= " for the unchecked boxes.

 

It seems like I'm missing something simple.

 

All help is appreciated!

 

B

 

Link to comment
Share on other sites

You will get nothing for unchecked checkboxes. How is the foreach() loop supposed to know that a checkbox isn't checked since the value isn't in the $_POST array? What you need to do is store the possible values in an array, and compare what is present in the $_POST array to the array of possible values. For example, if there were 10 checkboxes, with values from 0-9, you could do something like this.

 

$_POST['checkboxes'] = array( 4, 5, 6, 7); // simulated form data . . . 
$values = array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9); // Possible values of checkboxes
$not_checked = array_diff( $values, $_POST['checkboxes']); // compare values in $_POST['checkboxes'] array to possible values
print_r($not_checked); // lists values not present

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.