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.

Be Sociable, Share!
Boyko January 8, 2012 at 6:55 pm

Thanks, exactly what I needed!

Helen Neely January 9, 2012 at 1:19 pm

Great work. I keep coming back to this page whenever I run into something that needs sorting.

Thanks for having such a great tutorial.

Vitaliy Paritskiy January 18, 2012 at 9:36 pm

Great tutorial.

Thank you.

Maja January 23, 2012 at 11:32 am

What if I need for the user to check the box so the form is send like Accepting Terms and Conditions. And if they don’t check, error message to be displayed.

Morgan March 11, 2012 at 6:04 am

Should redirect to the page “error.php.”

Morgan March 11, 2012 at 7:38 pm

I did have a bunch of code in there, but it seems to have vanished. Go ahead and don’t approve either of these comments.

lft February 1, 2012 at 1:01 pm

Thanks

clinton February 3, 2012 at 5:46 am

how about multiplication table in where the user will input a 2 separated input in print it..

Exprentice February 14, 2012 at 10:15 am

Who needs snippets when you have great code like this on the internet. Truly a beautiful explanation of the whole process with great code.

Abeera February 23, 2012 at 1:00 pm

I want more than one check boxes to be selected….whats to do….?

Manurro February 24, 2012 at 3:33 am

Excellent.

BillsBayou March 2, 2012 at 6:35 pm

Perfect for what I needed to know. I just bookmarked your site.

Mujaid March 4, 2012 at 12:37 pm

Thank you very much, this what i was searching for…
thanks again

Bismark March 9, 2012 at 5:50 pm

Good presentation, my question is, I have a group of checkboxes and I need to ‘checked’ some of them. What function will do that?

inam101 March 12, 2012 at 4:48 am

very easy to read and understand tutorial. thanks a lot guys.

Meditaion March 12, 2012 at 8:52 am

Thanks a lot bro……

francis March 12, 2012 at 2:06 pm

Thanks for saving my ass, i appreciate it .. it is direct and clear!
thanks much again and again.

Andy March 15, 2012 at 4:56 pm

But if you use this method how do you get the values to stick on form submission so the checked appears?

Ali March 20, 2012 at 5:22 pm

Exactly, what i needed. Thanks a lot for this great tutorial :)

Wojtek March 21, 2012 at 9:49 am

That was useful. Thanks

deepanka March 23, 2012 at 6:27 am

Is there a problem if we give ‘formdoor[0],formdoor[1]…’ instead of ‘formdoor[]‘?

nawaz March 23, 2012 at 6:29 am

Thanks for this….

Comments on this entry are closed.

Previous post:

Next post: