html - How to read if a checkbox is checked in PHP?

ID : 10446

viewed : 44

Tags : phphtmlformspostcheckboxphp

Top 5 Answer for html - How to read if a checkbox is checked in PHP?

vote vote

96

If your HTML page looks like this:

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

After submitting the form you can check it with:

isset($_POST['test']) 

or

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

81

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">  
vote vote

75

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(... 
vote vote

67

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 }  
vote vote

56

$check_value = isset($_POST['my_checkbox_name']) ? 1 : 0; 

Top 3 video Explaining html - How to read if a checkbox is checked in PHP?

Related QUESTION?