You are here: Home » All Posts » PHP Form » Handling checkbox in a PHP form processor

Handling checkbox in a PHP form processor

in PHP Form

This tutorial will introduce HTML check boxes and how to deal with them in PHP.

Single check box

Let's create a simple form with a single check box.

<form action="checkbox-form.php" method="post">
    Do you need wheelchair access?
    <input type="checkbox" name="formWheelchair" value="Yes" />
    <input type="submit" name="formSubmit" value="Submit" />
</form>


In the PHP script (checkbox-form.php), we can get the submitted option from the $_POST array. If $_POST['formWheelchair'] is "Yes", then the box was checked. If the check box was not checked, $_POST['formWheelchair'] won't be set.

Here's an example of PHP handling the form:

<?php
if(isset($_POST['formWheelchair']) &&
   $_POST['formWheelchair'] == 'Yes')
{
    echo "Need wheelchair access.";
}
else
{
    echo "Do not Need wheelchair access.";
}
?>

The value of $_POST['formSubmit'] is set to 'Yes' since the value attribute in the input tag is 'Yes'.

<input type="checkbox" name="formWheelchair" value="Yes" />

You can set the value to be a '1' or 'on' instead of 'Yes'. Make sure the check in the PHP code is also updated accordingly.

Check box group

There are often situations where a group of related checkboxes are needed on a form. The advantage of check box group is that the user can select more than one options. (unlike a radio group where only one option could be selected from a group).

Let's build on the above example and give the user a list of buildings that he is requesting door access to.

<form action="checkbox-form.php" method="post">
Which buildings do you want access to?<br />
<input type="checkbox" name="formDoor[]" value="A" />Acorn Building<br />
<input type="checkbox" name="formDoor[]" value="B" />Brown Hall<br />
<input type="checkbox" name="formDoor[]" value="C" />Carnegie Complex<br />
<input type="checkbox" name="formDoor[]" value="D" />Drake Commons<br />
<input type="checkbox" name="formDoor[]" value="E" />Elliot House
<input type="submit" name="formSubmit" value="Submit" />
</form>

Please note that the checkboxes have the exact same name ( formDoor[ ] ). Also notice that each name ends in [ ]. Using the same name indicates that these checkboxes are all related. Using [ ] indicates that the selected values will be accessed by PHP script as an array. That is, $_POST['formDoor'] won't return a single string as in the example above; it will instead return an array consisting of all the values of the checkboxes that were checked.

For instance, if I checked all the boxes, $_POST['formDoor'] would be an array consisting of: {A,B,C,D,E}. Here's an example of how to retrieve the array of values and display them:

<?php
  $aDoor = $_POST['formDoor'];
  if(empty($aDoor))
  {
    echo("You didn't select any buildings.");
  }
  else
  {
    $N = count($aDoor);
    echo("You selected $N door(s): ");
    for($i=0; $i < $N; $i++)
    {
      echo($aDoor[$i] . " ");
    }
  }
?>

If no checkboxes are checked, $_POST['formDoor'] will not be set, so use the "empty" function to check for this case. If it's not empty, then this example just loops through the array ( using the "count" function to determine the size of the array ) and prints out the building codes for the buildings that were checked.

If the check box against 'Acorn Building' is checked, then the array will contain value 'A'. similarly, if 'Carnegie Complex' is selected, the array will contain C.

Check whether a particular option is checked

It is often required to check whether a particular option is checked out of all the available items in the checkbox group. Here is the function to do the check:

function IsChecked($chkname,$value)
    {
        if(!empty($_POST[$chkname]))
        {
            foreach($_POST[$chkname] as $chkval)
            {
                if($chkval == $value)
                {
                    return true;
                }
            }
        }
        return false;
    }

In order to use it, just call IsChecked(chkboxname,value). For example,

if(IsChecked('formDoor','A'))
{
//do somthing ...
}
//or use in a calculation ...
$price += IsChecked('formDoor','A') ? 10 : 0;
$price += IsChecked('formDoor','B') ? 20 : 0;

Download Sample Code

Download the PHP form checkbox sample code:
php-form-checkbox.zip.

Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Blogplay

Related posts:

  1. HTML form input examples

{ 68 comments }

Emmanuel August 14, 2011 at 5:09 pm

Peace! This code is helpful but i’m having a problem because the one i’m doing is the other way around. i want to make a php code that will notify someone that he didn’t chose any option, a notice that he has chosen a certain option and a notice that will say that he can’t chose all the options. please help. thanks and more power!

el dorado family August 16, 2011 at 7:38 am

..hey.!i like your samples…but i need some of it..
is itok..?

web-developer August 16, 2011 at 1:30 pm

Thank you, it is great article.
The only thing I want to say that you can change this line:
for($i=0; $i < $N; $i++)
into foreach syntax. It would be more correct and more readable IMHO.

Christopher September 14, 2011 at 3:58 am

True. the code would be more concise. either way works but I tend to use foreach in this situation too.

newbie October 1, 2011 at 2:23 am

Foreach works too but the for loop is much faster than the foreach.. :)

PHP courses August 31, 2011 at 11:17 pm

I’ve been searching the net all night looking for an example like this.  I’m taking a PHP Course and my tutor has given me an assignment and I’m trying to figure out how to handle checkboxes.

gsi September 12, 2011 at 10:14 am

anyway that I can get the unchecked checkboxes?

Christopher September 14, 2011 at 3:57 am

Thanks man.. it’s been a looong night, and I just couldn’t recall how to handle checkboxes for the life of me, lol.. you know how it goes :-)

Joy September 19, 2011 at 4:49 pm

Hi,

I’m using the isset and it’s not working for me at all! My checkbox is always not set even when it has been checked. I have NO idea what the problem is – have you ever run across this before?
Thanks!

Prasanth September 28, 2011 at 3:25 pm

Check the checkbox name/id. It is case sensitive

Dre September 20, 2011 at 3:15 pm

 
Thing is..
 
if $_POST['formWheelchair'] isn’t set, then the IF will break.
 
Fact is, you need to firs check if the _POST var is set and only afterwards in a nested if do any other checks on the var.
 
if(isset($_POST['formWheelchair'])){
 
if($_POST['formWheelchair']){
//do the nasty
}
}
 
 

coupon forum September 26, 2011 at 10:07 am

you could also use foreach loop:
foreach($_POST['formDoor'] as $check){
..

}

josh September 27, 2011 at 10:15 pm

@gsi
you have an array of the checkboxes and then match against it to see if they were selected. EX:
$array = array(‘box1′,’box2′,’box3′,’box4′);
$checked_checkboxes = implode(‘,’,$_POST['checkboxes']);
foreach ($array as $item){
if(preg_match(‘/$item/’, $checked_checkboxes)){
echo “$item was checked”;
}
else{
echo “$item wasn’t checked”;
}
}

NOBODY October 5, 2011 at 3:09 pm

That was really helpfull, thank u so much
 
 
___________________________________
http://suvo.me

Helen Neely October 15, 2011 at 7:20 am

Thanks for this checkbox example. I was looking something that would handle multiple checkbox selection and this is definitely the exact solution for the problem.
Nice work.

Domonique November 3, 2011 at 6:44 pm

How can you tell if a checkbox isn’t checked in the formDoor[]?

vineesh November 24, 2011 at 8:20 am

i have created a registration form then it can displayed a table. i want to edit each selected field selection using checkbox.

Jimbo December 16, 2011 at 11:28 am

I have a large php form with about 30 fields a double radio button (alternative yes/no) and three checkboxes that activate dropdowns via javascript. They all work fine but I just cannot get a simple “terms ok” checkbox to transfer its value to the next php page. I have tried all the stuff above but nothing works – here is some code:

Page 1 with form

Page 2

if(isset($_POST['chkTerms']) && $_POST['chkTerms'] == “chk”){
$chkTerms = “chk”;
}
else
{
$chkTerms = “nochk”;
}

and a hidden field for later use on this page
<body etc…
<form stuff…

<input name="chkTerms" type="hidden" value="” />

It always throws “nochk”. WHY?

Jimbo December 16, 2011 at 11:31 am

RE the code I just added – the second page code is

<input name="chkTerms" type="hidden" value="” />

Hope this code shows unless the anti-injection routine kills it!

pullarao k December 20, 2011 at 10:44 am

my problem is displaying the multiple check boxes in the same line for displaying the week days as sunday monday tuesday…………… instead of displaying vertical wise.
help me to display the days in horizontal checkboxes ..

Saeed Neamati December 21, 2011 at 6:32 am

You have said that using [] makes PHP give us an array, instead of a simple string (simple value). Is it an HTTP attribute, or a PHP attribute. As much as I know, browsers won’t (can’t) send POST body as an array. Thus this may mean that the server side language, be it PHP or ASP.NET or other languages, should check the parameter name, and if it ends in [] then they should parse the value using ‘,’ mark.

Prasanth December 28, 2011 at 3:15 pm

Your understanding is incomplete: PHP can receive input values as array.

Sk December 30, 2011 at 3:36 pm

Please tell me how to solve this:

I have a form where visitor can check multiple categories, multiple post type and multiple author to be retrieved from the database.

Your method is getting me outputs one category after the other. As I have to put the whole mysql query inside the for loop.

But what i need is like this:

$res = mysql_query(“SELECT * FROM jobposts WHERE (category = ‘checked-category1′ && category = ‘checked-category2′ && category = ‘checked-category3′ && author = ‘checked-author1′ && author = ‘checked-author1′ && posttype = ‘checked-posttype1′ && ) ORDER BY id DESC”)

I did it several times in past. but now after a few years gap I suddenly feeling being no where. Please help me.

Thanks in advance

spylockout January 7, 2012 at 7:28 pm

thx,
would have used an old for loop to check over if one of my 100 check boxes (oh i know how *Censored* this is) was set.

Comments on this entry are closed.

Previous post:

Next post: