POST arrays not showing unchecked Checkboxes

That behavior is not surprising, as the browser doesn’t submit any value for checkboxes that are unchecked.

If you are in a situation where you need to submit an exact number of elements as an array, why don’t you do the same thing you do when there’s an id of some sort associated with each checkbox? Just include the PHP array key name as part of the <input> element’s name:

  <tr>
                                                       <!-- NOTE [0] --->
      <td class="bla">Checkbox: <input type="checkbox" name="cBox[0]"/></td>
  </tr>
   <tr>
      <td class="bla">Checkbox: <input type="checkbox" name="cBox[1]"/></td>
  </tr>
   <tr>
      <td class="bla">Checkbox: <input type="checkbox" name="cBox[2]"/></td>
  </tr>

That still leaves you with the problem that unchecked boxes will still not be present in the array. That may or may not be a problem. For one, you may really not care:

foreach($incoming as $key => $value) {
    // if the first $key is 1, do you care that you will never see 0?
}

Even if you do care, you can easily correct the problem. Two straightforward approaches here. One, just do the hidden input element trick:

  <tr>
      <td class="bla">
        <input type="hidden" name="cBox[0]" value="" />
        Checkbox: <input type="checkbox" name="cBox[0]"/>
      </td>
  </tr>
   <tr>
      <td class="bla">
        <input type="hidden" name="cBox[1]" value="" />
        Checkbox: <input type="checkbox" name="cBox[1]"/>
      </td>
  </tr>

And two, which I find preferable, fill in the blanks from PHP instead:

// assume this is what comes in:
$input = array(
    '1' => 'foo',
    '3' => 'bar',
);

// set defaults: array with keys 0-4 all set to empty string
$defaults = array_fill(0, 5, '');

$input = $input + $defaults;
print_r($input);

// If you also want order, sort:

ksort($input);
print_r($input);

See it in action.

Leave a Comment