Whenever a checkbox is used in PHP script then in order to retain its previous value we need to write if-else statement. An example of this type of situation is as follows:
<input type=checkbox name=agree value=yes <?php if($agree==’yes’) echo ‘checked’; ?>>
So in this case if the form has been submitted without clicking on this checkbox then it will remain unchecked after form submission. However if the form has been submitted after clicking the checkbox then it will remain checked after form submission.
Now we can simplify the above code as follows:
<input type=checkbox name=agree value=checked <?php echo $agree; ?>>
The trick here is that we have set the word “checked” as the value of the variable. So if the checkbox has been checked and then the form has been submitted then the value of the variable $agree will become equal to “checked” and so after form submission it will remain checked. However if the form has been submitted without checking this checkbox then it will remain unchecked. By setting the value of the checkbox variable to “checked” we can remove the if statement to simplify the PHP code.