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">
To check if a checkbox is checked use empty()
When the form is submitted, the checkbox will ALWAYS be set, because ALL POST variables will be sent with the form.
Check if checkbox is checked with empty as followed:
//Check if checkbox is checked
if(!empty($_POST['checkbox'])){
#Checkbox selected code
} else {
#Checkbox not selected code
}
Wordpress have the checked()
function.
Reference: https://developer.wordpress.org/reference/functions/checked/
checked( mixed $checked, mixed $current = true, bool $echo = true )
Description Compares the first two arguments and if identical marks as checked
Parameters $checked (mixed) (Required) One of the values to compare
$current (mixed) (Optional) (true) The other value to compare if not just true Default value: true
$echo (bool) (Optional) Whether to echo or just return the string Default value: true
Return #Return (string) html attribute or empty string
Learn about isset
which is a built in "function" that can be used in if statements to tell if a variable has been used or set
Example:
if(isset($_POST["testvariabel"]))
{
echo "testvariabel has been set!";
}
filter_input(INPUT_POST, 'checkbox_name', FILTER_DEFAULT, FILTER_FORCE_ARRAY)
$check_value = isset($_POST['my_checkbox_name']) ? 1 : 0;