Solving the HTML Checkbox Problem

Published 28th June 2010

A problem I’ve come across recently involves processing HTML checkboxes in PHP. The problem isn’t too easy to explain so I will demonstrate with an example.

The Problem

You have the following HTML which is fine:

<input type="checkbox" id="some_checkbox" name="some_checkbox" />

When you then submit your form you want to get the value of the checkbox in PHP by doing:

$_POST['some_checkbox'];

This is all fine. Except the $_POST value for “some_checkbox” only exists when the checkbox is ticked. When ticked the value will be “on”. Otherwise the $_POST value doesn’t even exist in the array.

“Ok so what’s the problem with that exactly?” I hear you say. Well imagine you are processing a huge form and saving options in a database. You don’t want to set the values individually so you loop through the $_POST array and set the values that way. Something like the following:

$options = array(); foreach( $_POST as $key => $val ){ $options[$key] = $val; } update_database( $options );

Fantastic. However as I mentioned above the $_POST[‘some_checkbox’] value only exists when the checkbox is ticked. So when ticked the value is set to “on”, however when it is not ticked the database value doesn’t get updated (because the $_POST value is not set). See the problem?

The Solution

So whats the solution. Well it’s actually fairly simple and quite clever:

<input type="hidden" name="some_checkbox" value="off" /> <input type="checkbox" name="some_checkbox" value="on" />

As you can see you simply add an extra hidden input with the same name as the checkbox. This way when the checkbox is un-ticked the value of $_POST[‘some_checkbox’] will be “off” and when the checkbox is ticked the value will be overridden as “on”. Simple.