How to read if a checkbox is checked in PHP? – Dev

The best answers to the question “How to read if a checkbox is checked in PHP?” in the category Dev.


How to read if a checkbox is checked in PHP?


Zend Framework use a nice hack on checkboxes, which you can also do yourself:

Every checkbox generated is associated with a hidden field of the same name, placed just before the checkbox, and with a value of “0”. Then if your checkbox as the value “1”, you’ll always get the ‘0’ or ‘1’ value in the resulting GET or POST

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


If your HTML page looks like this:

<input type="checkbox" name="test" value="value1">

After submitting the form you can check it with:



if ($_POST['test'] == 'value1') ...


Let your html for your checkbox will be like

<input type="checkbox" name="check1">

Then after submitting your form you need to check like

if (isset($_POST['check1'])) {

    // Checkbox is selected
} else {

   // Alternate code

Assuming that check1 should be your checkbox name.And if your form submitting method is GET then you need to check with $_GET variables like

if (isset($_GET['check1'])) {

   // Checkbox is selected


When using checkboxes as an array:

<input type="checkbox" name="food[]" value="Orange">
<input type="checkbox" name="food[]" value="Apple">

You should use in_array():

if(in_array('Orange', $_POST['food'])){
  echo 'Orange was checked!';

Remember to check the array is set first, such as:

if(isset($_POST['food']) && in_array(...