benphp Posted July 29, 2011 Share Posted July 29, 2011 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 Quote Link to comment https://forums.phpfreaks.com/topic/243214-how-to-populate-array-values-from-a-single-checkbox/ Share on other sites More sharing options...
Pikachu2000 Posted July 29, 2011 Share Posted July 29, 2011 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 Quote Link to comment https://forums.phpfreaks.com/topic/243214-how-to-populate-array-values-from-a-single-checkbox/#findComment-1249154 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.