⊗ppPmFmChcN 307 of 447 menu

Nuances of Using Checkboxes in PHP

Suppose our form has only a checkbox:

<form action="" method="GET"> <input type="checkbox" name="flag"> <input type="submit"> </form>

Suppose the form processing code looks like this:

<?php if (!empty($_GET)) { // if the form was submitted if (isset($_GET['flag'])) { // if the checkbox is checked echo 'checked'; } else { echo 'not checked'; } } ?>

We face a problem - if the checkbox is not checked, then, since there are no other elements in the form besides the checkbox, an empty array will be stored in $_GET. This means that in the form processing code we will not enter the first if, which checks the form submission.

To solve the problem, a special technique is used: create a hidden input with the same name as our checkbox. In this case, the value of the hidden input is set to zero, and the checkbox's value to one:

<form action="" method="GET"> <input type="hidden" name="flag" value="0"> <input type="checkbox" name="flag" value="1"> <input type="submit"> </form>

In this case, the following will happen. If the checkbox is not checked, then only the value of the hidden input will be sent to the server. If the checkbox is checked, then both values with the same name will be sent to the server. But, since the checkbox's value will be the second one, it will simply overwrite the first one.

So, now our checkbox will send either zero or one to the server:

<?php var_dump($_GET['flag']); // '0' or '1' ?>

Let's use this in our check:

<?php if (!empty($_GET)) { if ($_GET['flag'] === '1') { echo 'checked'; } else { echo 'not checked'; } } ?>

Using a checkbox, ask the user if they are already 18 years old or not. If they are, grant them access to the site, and if not, deny access.

byenru