PHP to check if a checkbox is checked
PHP Code to Check if a Checkbox is Checked
if (isset($_POST['checkbox_name']) && $_POST['checkbox_name'] === 'on') {
// Checkbox is checked
} else {
// Checkbox is not checked
}
How it works
isset()
checks if a variable or array key is set and is notNULL
. In this case, it checks if the form field with the namecheckbox_name
exists and is not empty.$_POST
is a global array that stores the data sent through an HTML form using the POST method.===
is a strict equality operator that checks for both equality in value and type. In this case, it checks if the value of the checkbox is exactly equal to the string'on'
.
Implementation
To implement this code, you need to:
- Add the necessary HTML checkbox to your form. For example:
<input type="checkbox" name="checkbox_name" value="on">
- Add the PHP code to your server-side script. For example, in a PHP file that processes the form submission:
<?php
if (isset($_POST['checkbox_name']) && $_POST['checkbox_name'] === 'on') {
// Checkbox is checked
} else {
// Checkbox is not checked
}
?>
- Use CSS to style the checkbox as desired.