See if a Checkbox is Checked in PHP

Short totorial on how to work with checkboxes in HTML and PHP.

12865 views

Edited: 2020-03-03 23:42

PHP article image

Checkboxes can be used in HTML forms to control settings related to whatever is being posted back to the server. For example, if you are creating a new blog post from a HTML form, checkboxes can be used to control whether certain data should be hidden or shown to your visitors when viewing the blog post.

If a checkbox is checked, the value will be included in the post. Therefor, keeping a static value of 1 should be sufficient in most cases. The name attribute allows you to distinguish the box from other form elements, so the value is not really that important.

To check a checkbox you can use the checked attribute, or alternatively avoid including it to leave the checkbox unchecked.

In your HTML, a checkbox should look like these below (all valid examples).

<input type="checkbox" name="mycheckbox" value="1" checked="checked">
<input type="checkbox" name="mycheckbox" value="1" checked>

Styling and placement of form elements is not part of this tutorial.

Note. Extra care should be taken to make sure your HTML form elements are accessible.

Form labels should have a for attribute that correspond with the ID of the input element that they are associated with.

Checking if a checkbox was checked

If a checkbox is checked, the value will be included in the HTTP POST and made available in the $_POST superglobal array. So, to find out if a box was checked, we can use an if statement to see if mycheckbox is found in the $_POST array. You can either use empty, or isset. It does not really matter, as long as you understand behavioral differences.

if (empty($_POST['mycheckbox'])) {
  echo "Checked!";
} else {
  echo 'Not checked!';
}

The above looks rather messy if you have a lot of code, so you may want to shorten the if statement, and keep it down to one line. The below will set the $my_checkbox variable to 1 if your checkbox is checked, or an empty string if not checked.

$my_checkbox = (empty($_POST['mycheckbox'])) ? 1 : '';

Since we are not using the value from our checkbox, the $my_checkbox variable can safely be inserted directly into a database without validation.

Tell us what you think:

  1. The best way to deal with a trailing question mark is probably just to make it a bad request, because it is a very odd thing to find in a request URL.
  2. This happens when trying to access methods on objects that are not instantiated. Always check if an object is instantiated before trying to use it.
  3. Tutorial on how to use proxy servers with cURL and PHP
  4. How to determine an optimal value for pm.max_children and related php-fpm settings for your server and web applications.
  5. PSR-1 does not permit underscores for method names, but it probably should. Also, class names most use StudlyCaps.

More in: PHP