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 not NULL. In this case, it checks if the form field with the name checkbox_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:

  1. Add the necessary HTML checkbox to your form. For example:
<input type="checkbox" name="checkbox_name" value="on">
  1. 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
}
?>
  1. Use CSS to style the checkbox as desired.