Saving the Selected Value in a Checkbox After Submission in PHP
Let's now make it so that the value
of the checkbox is saved after submission. For
this, we will check that $_GET['flag']
exists (meaning the form was submitted)
and is equal to one (meaning the checkbox is checked).
If these two conditions are met, then we output
the checked attribute in the checkbox:
<form action="" method="GET">
<input type="hidden" name="flag" value="0">
<input
type="checkbox"
name="flag" <?php
if (isset($_GET['flag']) and $_GET['flag'] === '1')
echo 'checked';
?>
>
<input type="submit">
</form>
The check can be simplified if we know for sure
that the hidden input sends 0. In this
case, if the checkbox is not checked, then $_GET['flag']
will contain '0', and if the form
has not been submitted yet, it will contain null.
In both of these cases, we should not output
checked. And we can catch both of these
cases with the empty function. Thus,
we can check that $_GET['flag']
is not empty, and only in this case output checked:
<form action="" method="GET">
<input type="hidden" name="flag" value="0">
<input
type="checkbox"
name="flag"
value="1"
<?php if (!empty($_GET['flag'])) echo 'checked' ?>
>
<input type="submit">
</form>
Make three checkboxes that will preserve their value after submission.