You are on page 1of 19

Handling checkbox in a

PHP form processor


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;

i dont need to worry about checking if that are checked

they are only going to send the values to the server if they are checked.

lets say you have this:

Code: [ Select ] [ Line Numbers Off ]


1. <input type="checkbox" name="fruit" value="apples">apples
2. <input type="checkbox" name="fruit" value="oranges">oranges
3. <input type="checkbox" name="fruit" value="peaches">peaches
4. <input type="checkbox" name="fruit" value="mangos">mangos
If you check apples and oranges,

$HTTP_POST_VARS["fruit"] will be an array containing two values: apples and


oranges.
JackDaRippaZ
Newbie

Joined: Jun 25, 2004


Posts: 11
Status: Offline
July 28th, 2004, 4:15 pm
yeah nah i need to get the values from a checkbox array

i know how to post them to another page, but its putting them/sorting them into an
array or sorting through the array

please
Cafu
Student

Joined: Jul 15, 2004


Posts: 97
Status: Offline
July 28th, 2004, 6:09 pm
will this help?

Code: [ Select ] [ Expand ] [ Line Numbers Off ]


1. <html>
2. <head>
3. <title>checkbox help</title>
4. </head>
5. <?
6.
7. if (isset($HTTP_POST_VARS)) {
8.
9. $fruit = $HTTP_POST_VARS["fruit"];
10.
11. echo("Fruits chosen: " . count($fruit) . "<br><br>");
12.
13. if (count($fruit)>0) {
14. echo("You chose the following fruits:<br>");
15. }
16.
17. for ($i=0; $i<count($fruit); $i++) {
18. echo( ($i+1) . ") " . $fruit[$i] . "<br>");
19. }
20. }
21. ?>
22. <body bgcolor="#ffffff">
23.
24. <form method="post">
25. Choose a fruit:<br><br>
26. <input type="checkbox" name="fruit[]" value="apples">apples <br>
27. <input type="checkbox" name="fruit[]" value="oranges">oranges <br>
28. <input type="checkbox" name="fruit[]" value="peaches">peaches <br>
29. <input type="checkbox" name="fruit[]" value="mangos">mangos<br>
30. <input type="submit">
31. </form>
32.
33. </body>
34. <html>
drdrano
Born

Joined: May 23, 2007


Posts: 1
Loc: La Crosse, WI, USA
Status: Offline
May 23rd, 2007, 7:50 am
Apologies for posting to such an old thread, but my google search brought me here and I
found the info here helpful, although slightly flawed and a little dated. Others may arrive
here also needing help so I will contribute my 2cents.

I found Cafu's post above to be a good jumping off place. $HTTP_POST_VARS is now
deprecated and should be updated to the superglobal $_POST. I updated the code and
tweaked it a bit as I was learning how the code handles checkboxes. My notes are
included in the code.

Code: [ Select ] [ Expand ] [ Line Numbers Off ]


1. <!--
2. Instructive notes:
3. 1. to use the if (isset($_POST['submit'])) construct, the submit
button must have a name defined as 'submit'
4. 2. if each of the checkboxes has been named with the same name (ie
'fruit') followed by a pair of square brackets '[]',
5. when the form is submitted, the $_POST superglobal will have a variable
named $_POST['fruit'] that represents an
6. array containing array elements from only those checkboxes that have been
checked.
7. 3. count() returns the number of elements in an array. here it returns
'0' if no checkboxes are checked. This could be
8. because $_POST['fruit'] is not set, or because $_POST['fruit'] represents an
array that has been set but has no elements.
9. if we change the if statement to if (isset($_POST['fruit'])), the
statements in the 'if' block are never executed,
10. so $_POST['fruit'] is not set and must evaluate to null. count() accurately
returns '0' when its parameter is null.
11. 4. the value of each element in the array $_POST['fruit'] is determined
by the value attribute of each of the checkboxes.
12. 5. note that in the absence of an 'action = "some_script.php" attribute
in the form element, the browser reloads this script when the submit button is
clicked.
13.
14. -->
15. <html>
16. <head>
17. <title>checkbox help</title>
18. </head>
19. <?php
20. if (isset($_POST['submit'])) {
21. $fruit = $_POST["fruit"];
22. $how_many = count($fruit);
23. echo 'Fruits chosen: '.$how_many.'<br><br>';
24. if ($how_many>0) {
25. echo 'You chose the following fruits:<br>';
26. }
27. for ($i=0; $i<$how_many; $i++) {
28. echo ($i+1) . '- ' . $fruit[$i] . '<br>';
29. }
30. echo "<br><br>";
31. }
32. ?>
33. <body bgcolor="#ffffff">
34. <form method="post">
35. Choose a fruit:<br><br>
36. <input type="checkbox" name="fruit[]" value="apples">apples <br>
37. <input type="checkbox" name="fruit[]" value="oranges">oranges <br>
38. <input type="checkbox" name="fruit[]" value="peaches">peaches <br>
39. <input type="checkbox" name="fruit[]" value="mangos">mangos<br>
40. <input type="submit" name = "submit">
41. </form>
42. </body>
43. <html>
Larry Fundell
trekie8472
Born

Joined: Jun 03, 2007


Posts: 1
Loc: Minneapolis, MN
Status: Offline
June 3rd, 2007, 9:27 pm
Thank you for that update! It is exactly what I was looking for, and what a coincidence
that it was posted by somebody from my hometown of La Crosse.
murcielagossi
Proficient

Joined: Jul 28, 2006


Posts: 457
Status: Offline
June 5th, 2007, 3:11 pm
Or you could use "foreach":

PHP Code: [ Select ] [ Line Numbers Off ]


1.
2. foreach($_POST['check'] as $value) {
3.
4. $check_msg .= "Checked: $value\n";
5.
6. }
7.
8.

The accompanying form code would be:

Code: [ Select ] [ Line Numbers Off ]


1. <input type="checkbox" name="check[]" value="blue_color"> Blue<br>
2. <input type="checkbox" name="check[]" value="green_color"> Green<br>
3. <input type="checkbox" name="check[]" value="orange_color"> Orange<br>

It that doesn't clarify it enough --


http://www.kirupa.com/web/php_contact_form3.htm

/* My Logic Is Undeniable */
flann
Novice

Joined: Jun 13, 2006


Posts: 25
Loc: Wisconsin
Status: Offline
October 29th, 2007, 10:41 am
is there anyway to get all the checkboxes through a post, even the ones that aren't
checked? I too am from La Crosse .
ydajdaj
Born

Joined: Mar 11, 2010


Posts: 1
Status: Offline
March 11th, 2010, 12:38 pm
I could lend a hand? I have a table where values sakan...I would like to do is power
through checkboxes have the possibility to use the same value for multiple records.... I
am a rookie.!

Example I have a list of students who were loading a database, and these students are
assigned a rating of another database, as sometimes the ratings are the same selection
is engorosso scores again and again....

case 4:
/ / SCREEN FOR QUALIFYING

print "Input captured <font face=arial size=3> </ font> <br>";


print "<table border=1>";
print "<TR borderColor = #bgColor = ffffff #7799bb> ";
print "<td> <font face=arial size=3> CATEGORY </ font> </ td>";
print "DESCRIPTION <td> <font face=arial size=3> </ font> </ td>";
print "<td> <font face=arial size=3> UNIT </ font> </ td>";
print "<td> <font face=arial size=3> PRICE MN </ font> </ td>";
print "<td> <font face = arial size = 3> PRICE USD </ font> </ td> ";
print "<td> <font face=arial size=3> AMOUNT </ font> </ td>";
print "<td> <font face=arial size=3> RAMA </ font> </ td>";
print "</ tr>";
$ result2 = mysql_query ( "SELECT id_insumo, category, des_insumo, unity,
precio_unita river precio_unitario_usd, can not branch from tb_insumo where contract =
$ id_contrato ORDER BY category, des_insumo");
while ($ row2 = mysql_fetch_array ($ result2, MYSQL_ASSOC))
(
$ homologa_completo = 0;

print "<TR>";
print "<td> <font face=arial size=3> $ row2 [category] </ font> </ td>";
print "<td> <font face=arial size=3> $ row2 [des_insumo] </ font> </ td>";
print "<td> <font face=arial size=3> $ row2 [drive] </ font> </ td>";
print "<td> <font face=arial size=3>. number_format ($ row2 [precio_unitario],
2,. ,)."</ font> </ td> ";
print "<td> <font face=arial size=3>. number_format ($ row2 [precio_unitario_usd], 2,.
,)."</ font> </ td>";
print "<td> <font face=arial size=3>. number_format ($ row2 [can not], 2,. ,)."</
font> </ td>";
if ($ row2 [branch]! = "none")
(
print "<td> <font face=arial size=3> <A HREF = javascript & #058; popUp
(homologa.php? Id_insumo = $ row 2 [id_insumo])> $ row2 [branch] </ A> </ font>
</ td> ";
)
else
(
$ s1 = "id_insumo = $ row2 [id_insumo] & input = $ row2 [des_insumo]";
print "<td> <font face=arial size=3> <A HREF = javascript & #058; popUp
(homologa.php? id_insumo = $ row 2 [id_insumo])> Index </ A> </ font> </ td> ";
$ homologa_completo = 1;
)
print "</ tr>";
)
mysql_free_result ($ result2);

print "</ table>";


if ($ homologa_completo == 0)
(
print "To continue the monthly adjustment adjustment selections NEWS </ b>";
$ result = mysql_query ( "update tb_contrato September homologa_completo =" 1
"where id_contrato = $ id_contrato;");

)
break;

/ / PAGE SETUP
imprime_ajuste_mensual_1 ();
break;

.
Hii there

I had a query regarding capturing multiple checkbox values on the next page. That is if
i have a group of checkboxes with the same name and i select more than one checkbox
how to capture all those values on the next page using PHP. for example consider the
following

<input type = "checkbox" name="text" value = "topt1"'><br>


<input type ="checkbox" name= "text" value = "topt2"><br>
<input type = "checkbox" name="text" value = "topt3"'><br>
<input type = "checkbox" name= "text" value = "topt4"><br>

how to capture all the checked values on the next page for the checkbox group text

Please repsond to this question as soon as possible

Thanks

Ravi

#2
July 21st, 2004, 04:54 PM

JeffCT Join Date: Jan 2001


PHP & Ruby Developer Posts: 1,436
Time spent in forums: 5 h 36 m 40 sec
Reputation Power: 39

You need to add [] to the end of the variable name:

Code:

<input type = "checkbox" name="text[]" value = "topt1"'><br>


<input type ="checkbox" name= "text[]" value = "topt2"><br>
<input type = "checkbox" name="text[]" value = "topt3"'><br>
<input type = "checkbox" name= "text[]" value = "topt4"><br>

Then the checked values will be available through $_POST:

PHP Code:
foreach( $_POST['text'] AS $checked_value )
{
echo $checked_value
}

..

Getting Check box values using array in PHP


Many times we have to display a list of names or records for consideration and out of which user
can select any number of records for further action. Here we may not know exactly how many
records will be displayed as some time based on different conditions records will be collected from
a table. So we can list the records with a checkbox by the side of it and user can select any
number of recodes. We will have one unique id associated with each record and that will be used
as value of the check box. Here is the code to display a list and then you can select and submit to
see the result.

This is a server side solution and we can get the array value using client side JavaScript we can
also get the value of the array of checkboxes.
Note that if in your server settings global variables is set to OFF then you have to take care for
that.

John Mike Rone

Mathew Reid Simon


Select

// This is to collect box array value as global_variables is set off in PHP5 by default

$box=$_POST['box'];

while (list ($key,$val) = @each ($box)) {

echo "$val,";

echo "<form method=post action=''>";

echo "<table border='0'

cellspacing='0' style='border-collapse: collapse' width='100' >

<tr bgcolor='#ffffff'>

<td width='25%'><input type=checkbox name=box[] value='John'></td>

<td width='25%'>&nbsp;John</td>

<td width='25%'><input type=checkbox name=box[] value='Mike'></td>

<td width='25%'>&nbsp;Mike</td>

<td width='25%'><input type=checkbox name=box[] value='Rone'></td>

<td width='25%'>&nbsp;Rone</td>
</tr>

<tr bgcolor='#f1f1f1'>

<td width='25%'><input type=checkbox name=box[] value='Mathew'></td>

<td width='25%'>&nbsp;Mathew</td>

<td width='25%'><input type=checkbox name=box[] value='Reid'></td>

<td width='25%'>&nbsp;Reid</td>

<td width='25%'><input type=checkbox name=box[] value='Simon'></td>

<td width='25%'>&nbsp;Simon</td>

</tr>

<tr><td colspan =6 align=center><input type=submit

value=Select></form></td></tr>

</table>";

Capture form checkbox values into a PHP Array for processing

When a user fills out options in your form, there might be a list of checkboxes they can tick for
hobbies & interests, it could be useful to store these multiple choices into an array for storing.

Heres some sample HTML:

<inputtype="checkbox"name="hobbies[]"value="Snooker">Snooker

<inputtype="checkbox"name="hobbies[]"value="Shopping">Shopping

<inputtype="checkbox"name="hobbies[]"value="Fashion">Fashion

<inputtype="checkbox"name="hobbies[]"value="Cinema">Cinema

And once the form is submitted, heres the PHP to process it (for this example, it prints out their
choices):
//useaforeachlooptoreadanddisplayarrayelements

if(is_array($_POST['hobbies'])){

echo'Youselected:<br/>';

foreach($_POST['hobbies']as$a){

echo"<i>$a</i><br/>";

..

Easily code dynamic PHP checkboxes

The Dynamic checkbox object


How to check, uncheck, display and have fun with HTML checkbox objects using
PHP and Super Globals

Checkboxes are just html. Anybody can code them. Actually, checkboxes belong
somewhere between the open form element, and the close form element. The open
form element should have at least a name,method and action properties and
optionally an enctype property for file/image uploads. Just like this:

<form name="myForm" method="post" action="someScript.php">

checkbox code goes in here between the form tags

</form>
Given that our checkboxes are somewhere between the form open and close,
checkboxes are intended for use when more than one selection is possible. For
example, if you were subscribing to a list of online magazines, then you should
have checkboxes for folks to subscribe to as many magazines as they like. Here are
three fictitious magazines:

Geek World Online

Hawaiian Surfer

Boring Accounting

Obviously you would not want to receive the 'Boring Accounting' magazine, so you
would not check that checkbox. If you submit the form - magazineForm.php - the
checkboxes were on you would submit the value of 'on' for the name of the
checkbox you checked. If you did not check the box then the submitted value will
be 'off'. A little code will make this clearer:

Checkbox code
Here's the checkbox code for the above magazines:

<input type="checkbox" name="Geek_World_Online_Magazine"> Geek World Online

<input type="checkbox" name="Hawaiian_Surfer_Magazine"> Hawaiian Surfer

<input type="checkbox" name="Boring_Accounting_Magazine"> Boring Accounting

How to make the checkbox already checked


If you want to have a checkbox already ticked then you just put the word
'CHECKED' at the end of the html, within the checkbox html. The following
checkbox is like this, it is already checked:

<input type="checkbox" name="Geek_World_Online_Magazine" CHECKED>


Geek World Online

The above code snippet produces this actual effect:


Geek World Online

And the submitted value is ...


When you click the submit button the submitted value for checked boxes will be
'on'. Checkboxes that are not checked will be 'off'. If we submitted the
'Geek_World_Online_Magazine' CHECKED input as above then the variable
named '$Geek_World_Online_Magazine' will have a value of 'on'. OK, that's great,
how do we show that same value again if we need to?

Just ask the visitor to click the back button?


Not. Say the visitor checked the magazines they wanted, but they
had a mistake in their email address, so they had to complete the
form again. Not! It's much better just to show the form again -
include("magazineForm.php") - and populate it with the chosen
values. How?

Populating a checkbox with a PHP determined value


Initialize or capture
With checkboxes all you do is test for the value of the variable. If the value is 'on'
then you add the word 'CHECKED' to the html. We now use superglobals to
extract and set values for variables. This is one of several ways to capture or
initialize a value for a variable - keep in mind the value may be sent via $_GET,
$_POST, $_REQUEST, $_COOKIE or other way (read manual) :

// initialize or capture the value

$Geek_World_Online_Magazine = !isset($_POST["Geek_World_Online_Magazine"]?
NULL: $_POST["Geek_World_Online_Magazine"];

The effect of this code is to retrieve the value for the variable. Our condition tests
if a variable is set for 'Geek_World_Online_Magazine'. If this variable does not
exist (a set variable with no value would cause our condition to evaluate to true)
then place a value of NULL into $Geek_World_Online_Magazine. Otherwise, grab
the value resulting from a post only.

Ternary operator
The Ternary operator may seem like a veil of obscurity, but after a few years its a
thing of beauty:
$variable = ( condition ) ? "value if condition is true" : "value if condition is
false" ;

condition may be any expression that resolves to true


or false

value may be any string, or variable or expression


that resolves to some value or NULL

... so now we have initialized or captured the posted value of 'on'


for the variable named $Geek_World_Online_Magazine. Now we
show that value:
Show the captured value
The code looks like this:

<input type="checkbox" name="Geek_World_Online_Magazine" <?php


if($Geek_World_Online_Magazine == "on"){echo " CHECKED";}?>> Geek World
Online

The code should produce this:

Geek World Online

Sure, but let's REALLY try the post

check or uncheck any checkboxes

submit them and see the same choices again

<!-- START of magazineForm.php -->

Subscribe to Fictitious Magazines here


Geek World Online

Hawaiian Surfer

Boring Accounting
Submit

Jump to source code section


<!-- END of magazineForm.php -->

And there you have seen the value for a checkbox variable, from
the beginning to almost the end.

Let's see the Source Code!

slightly scrambled source code for magazineForm.php -


there should NOT be any wrapping!:

<table bgcolor="honeydew">
<tr>
<td>
<?php echo"&lt;!-- START of magazineForm.php --&gt;";?>
<form name="magazineForm" method="post"
action="articleCheckbox.php">
<input type="hidden" name="resultsPlease"
value="Right Now!">
<h3>Subscribe to Fictitious Magazines here</h3>
<input type="checkbox"
name="Geek_World_Online_Magazine"<?php if($Geek_World_Online_Magazine
== "on"){echo" CHECKED";}?>> Geek World Online<br>
<input type="checkbox"
name="Hawaiian_Surfer_Magazine"<?php if($Hawaiian_Surfer_Magazine == "
on"){echo" CHECKED";}?>> Hawaiian Surfer<br>
<input type="checkbox"
name="Boring_Accounting_Magazine"<?php if($Boring_Accounting_Magazine
== "on"){echo" CHECKED";}?>> Boring Accounting<br>
<input type="submit" name="submit" value="Submit">
</form>
<a href="#source">Jump to source code section</a><br>
<?php echo"&lt;!-- END of magazineForm.php --&gt;";?>
</td>
</tr>
</table>

Sure, add another property to the checkbox


Making it more complicated than it has to be
You can also add the property of 'value' to checkboxes. With this you then have
three object properties: type, name and value. The only difference is you test for
the value you set.

Example. If you set this value:


<input type="checkbox" name="Geek_World_Online_Magazine" value="subscribe"
CHECKED>

... then you would test for the value (after capturing the value),
like:

<input type="checkbox" name="Geek_World_Online_Magazine" <?php


if($Geek_World_Online_Magazine == "subscribe"){echo " CHECKED";}?>> Geek
World Online

That's it for one checkbox. Add as many more as you like, but be
sure to keep the property called name different for each checkbox
you have.

You might also like