Last Updated: February 25, 2016
·
946
· codegefluester

Unchecked Checkboxes missing in $_POST when not checked

When a HTML checkbox is not checked, it wont be present in $_POST in the receiving script.

Usually you would do something like this:

if(isset($_POST['myCheckbox'])) {
     // Checkbox was not checked, set value to 0
     $myCheckboxValue = 0;
}

Instead just add a hidden input field with the same name as the checkbox to your HTML and set your unchecked value there:

<input type="hidden" name="myCheckbox" value="0" />
<input type="checkbox" name="myCheckbox" value="1" />

As there can be only one myCheckbox in the $POST array, $POST['myCheckbox'] will be 0 if the real checkbox is not checked but will be 1 if it is checked as the second input field will overwrite the previous one.