PHP: Checkbox Array in Form Handling – Multiple Checkbox Values in an Array

by Yang Yang on January 31, 2009

Checkboxes is probably one of the most frequently used form controls which come handy in dealing with one to many relationships.

The multiple selective nature of HTML form checkboxes require a convenient way for PHP to process multiple checkbox values, ideally in a single array.

By default, each and every HTML input control including checkboxes posts its value to server-side PHP script by a unique identity that is specified by attribute name=”variable-A”. This approach is generally fine with simple pairs of name and value. However, with multiple checkboxes in the form and probably a lot of them, you will need to assign every single one of them a different name which is quite bitsy and not neat at all.

The solution is for PHP to identify the entire series of checkboxes as a single array accessible via a common index in $_POST. This is achievable by simply inserting the array index operator ‘[]’ to the name attribute of the checkbox control:

<input type="checkbox" name="tags[]" value="1" />
<input type="checkbox" name="tags[]" value="2" />
<input type="checkbox" name="tags[]" value="3" />
<input type="checkbox" name="tags[]" value="4" />

This way, the PHP script processing POST will figure it out automatically and treat $_POST['tags'] as an array containing the values 1, 2, 3 and 4:

print_r($_POST['tags']);
// output
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
)

Now much more handy, huh!

Subscribe to Kavoir: blog feed

You should also read:

Kyle September 3, 2009 at 10:30 pm

Thanks!

od3n February 15, 2010 at 11:25 pm

i cant get the output run. how to do that?

jason September 30, 2011 at 3:41 pm

ABNormAL. . .

od3n February 15, 2010 at 11:33 pm

edited : weird, got it done.

Yang Yang February 26, 2010 at 4:26 pm

lol~

Jonas Ferreira February 25, 2010 at 12:21 am

And if you want the results of this array, is printed in a comma separated list for use in a query by example, just do this:

:)

Jonas Ferreira February 25, 2010 at 12:21 am

I think not left….

substr(implode(‘, ‘, $_POST['tags']), 0);

Yang Yang February 25, 2010 at 11:06 am

Nice tip, thanks! :)

Jim September 29, 2010 at 1:22 am

Thank you!
YOU solved my problems =D

Thomas December 3, 2010 at 9:21 am

Adding the [] seems to make it impossible for Javascript to do anything with the field, though, and I’m trying to use my checkboxes with both JS and PHP! But thanks!

Len January 12, 2011 at 12:05 pm

I’ve run into the same problem that Javascript fails when I add the [ ] to make PHP work. Does anyone know what needs to be done to make both work??

Reuben Chovuchovu April 1, 2013 at 11:46 pm

Give the checkbox an id or class for manipulation by javascript or jquery.

Beno Netto December 21, 2010 at 11:34 am

wow!
That ‘ s so simple!
I’m trying to do this like an hour!

Thanks!

laila March 5, 2011 at 7:46 pm

thanks a lot.
my Problem is now solved.

Now I can omplite my job..

regards

Chris April 16, 2011 at 12:52 am

To validate the fields with javascript before processing with php all you need to do is apply a unique id name to the fields. This will allow php to have it’s own reference name and JS to have it’s own.

hope that helps

Neri October 2, 2011 at 2:29 pm

Thanks, useful :D

Pankaj December 15, 2011 at 7:46 pm

Thanks .. very use full tutorial..

Sudip Samajder March 6, 2012 at 10:47 am

Thanks a lot. its awesome

Calis March 15, 2012 at 6:48 pm

Hoi,

Thanks, saved me a lot of time! To return the favor, here’s the script for building the checkboxes and using the array to insert in mysql.

//PHP function to create my checkboxlist with skills
function skillsList()
{
$dbc = getDBConnection();

$sql = “SELECT id,skill FROM skills ORDER BY id ASC”;
if($result = $dbc->query($sql)) {
while($row = $result->fetch_assoc())
/* Milk*/
$dropdown .= “”.$row['skill'].”";
}
$dbc->close();
return $dropdown;
}

PHP page to catch the form
/* SKILLS */
$skillsArray = ($_POST['skills']);

for($iSkill = 0; $iSkill < sizeof($skillsArray); ++$iSkill)
{
//echo ('SKILL '.$iSkill .' – value: '.$skillsArray[$iSkill].'’);
$sql = “INSERT INTO skills_person (person,skill_id) VALUES(‘”.$initials.”‘,’”.$skillsArray[$iSkill].”‘)”;

$dbc = getDBConnection();
$result = $dbc->query($sql);
$dbc->close();
}

Calis March 15, 2012 at 8:07 pm

function skillsList()
{
$dbc = getDBConnection();

$sql = “SELECT id,skill FROM skills ORDER BY id ASC”;
if($result = $dbc->query($sql)) {
while($row = $result->fetch_assoc())
$dropdown .= “”.$row['skill'].”";
}
$dbc->close();
return $dropdown;
}

shoaib April 5, 2012 at 2:41 pm

great code for check box sellection

Solar Panels Installer July 4, 2012 at 10:03 pm

it can be by followings:

$tags = $_POST['tags'];

for($i=0;$i<size($tags);$i++)
{
echo $tags[$i];
}

Ali August 3, 2012 at 6:39 pm

Hi Guys,

Looking for some desperately.

I am new to php, with a lot search I have been able to put together some form of working script. The problem I am now facing is I have multiple checkboxes for the users to select from but the selected checkbox value does not get inserted into the table instead shows as “Array”. With some help I plan to get all the selected checkbox values into one table.

I have two files one “testpage.html” which contains the form and the other “test_post.php” to process the form data. Please find below html and php file codes. Have to // in front of every code in html so the code can be seen.

Really appreciate your help in advance.

HTML form:
//
//
//
//

//Full Name:
//
//Mobile Number:
//
//Email Address:
//
//Residence Address:
//
//Which animal do you want to keep?
//Dog
//Cat
//Lion
//Tiger
//Leopard
//
//
//
//
//
//

PHP code:
$value)
$sql=”INSERT INTO $tbl_name(FullName, Number, EmailAddress, Address, petathome)VALUES(‘$_POST[$FullName[‘, ‘$_POST[$Number]‘,’$_POST[$EmailAddress]‘,’$_POST[$Address]‘,’$_POST[$petathome]‘)”;
$result=mysql_query($sql);

// if successfully insert data into database, displays message “Successful”.
if($result){
echo “Successful”;
echo “”;
echo “Back to main page“;
}

else {
echo “ERROR”;
}
?>

Graham October 6, 2012 at 9:18 pm

Many thanks – just what I needed!

iSoTürK March 22, 2013 at 9:58 pm

thanks bro :)

Comments on this entry are closed.

{ 3 trackbacks }

Previous post:

Next post: