Using checkboxes with PHP.

This is a beginners tutorial on how to handle HTML checkboxes with PHP.

Before you attempt to process checkbox values with PHP, there are a few important things that you will need to know:

  • The name that you assign to your checkbox won’t exist as a POST variable if the checkbox in question hasn’t been ticked by the user. If you are not careful with this, it may result in a nasty undefined index error! To guard against this, you will need to check to see if the POST variable has been set before you attempt to check its value.
  • Checkboxes should only be used for multiple choice options. In use cases where a SINGLE choice must be made, a radio button or a select option will work better. Remember: Web users associate checkboxes with “multiple choices”.

Single Checkbox Example

In this “Terms and Conditions” example, we process a single checkbox with PHP.

As you can see, we had to check to see if the POST variable “terms_of_service” existed. We did this by using the isset function. If the name of the checkbox exists as a POST variable, then it is safe to assume that the user has ticked it.

But what about multiple choice checkboxes? Well, that’s a little more complex…

Multiple Checkboxes & PHP.

In this example, we allow our users to select their favourite fruits:

Step-by-step explanation:

  1. We set up a “whitelist array”, which contains all of the checkbox values that the user is allowed to select. This is important as we don’t want to find ourselves in a situation where a user is modifying our form values with Firebug or Chrome’s Developer Tools (this would allow them to add checkbox options that don’t exist).
  2. We created an empty PHP array called $fruits. Once the form has been processed, this array will contain all of the values that the user has ticked.
  3. If you are using grouped / multiple choice checkboxes, then it is important to note that your POST variable will be an array.
  4. In the example above, we loop through this POST array containing the selected checbox values. We also validate them by making sure that they are in our whitelist array ($fruitOptions).
  5. If you look at the form, you’ll see that we named each checkbox “fruits[]”. The square brackets tell PHP that these checkbox values should be held in an array.

Facebook Comments