PHP Read checkboxes

June 18th, 2012

Reading simple text fields from a database is simple.
But what happens if you want to process boolean (true or false) values and show them as a checkbox?
With a little HTML knowledge and a simple PHP function, processing checkboxes is easy.

HTML Checkboxes

The first step is to understand how to ‘tick’ a checkbox in HTML.
Here’s an example of a form with two checkboxes

<form method="post" action="">
<input type='checkbox'>
<input type='checkbox' checked='yes'>
</form>

Note that the second checkbox has the added line “checked=’yes'” which, as you’ve probably guessed, ticks the checkbox.

PHP Checkbox array

We need some data with which to work.
I quickly created this array for the demo, but you could just as easily use a database to populate your form.
Name and Age are text fields, but Over18 is the boolean field we will use to populate our checkbox. The only values allowed are 0 and 1.

Note: You don’t need to copy and paste this yet; I have the completed version for download at the bottom of the page.

<?

$array[] = array(
"Name" => "Peter",
"Age" => 16,
"Over18" => 0
);

$array[] = array(
"Name" => "David",
"Age" => 21,
"Over18" => 1
);

$array[] = array(
"Name" => "James",
"Age" => 32,
"Over18" => 1
);

?>

Create the HTML

The next step is to create the HTML.  You’ll notice that I stop part way through and there’s a good reason for that…

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>PHP read checkbox values</title>

</head>

<body>

<form method="post" action="">

<table border="1" cellpadding="2" cellspacing="2">

<tr>
    <th>Name</th>
    <th>Age</th>
    <th>Over 18?</th>
</tr>

PHP Checkbox Loop

The reason I stopped the HTML early was because I am now going to insert a PHP loop to retrieve the array values we created earlier.

The following picture is a screenshot from my IDE editor and it shows what is happening.
The table sections are shown in green and the PHP Loop is shown in orange.
We create the HTML table, then use PHP to output the values of our array which we turn into table cells.  After the foreach loop has finished, we close the table down by using the closing tag.

PHP Checkbox function

You may notice that a function “is_checked()” is being called in the above code.
We need a function to determine whether we need to use tick our checkbox. if the value passed is “1”, we need to tick the box. Here’s the function:

<?

function is_checked($value) {
    if ($value == 1) 
        return "checked='yes'";        
} 

?>

People find this bit complicated. If you don’t understand the above, run the code and view the source of the page to view the output.

Click here to download the PHP Checkbox read checkboxes demo