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

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!

28 comments

  1. Kyle

    Thanks!

  2. od3n

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

    • jason

      ABNormAL. . .

  3. od3n

    edited : weird, got it done.

  4. Jonas Ferreira

    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:

    :)

  5. Jonas Ferreira

    I think not left….

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

  6. Jim

    Thank you!
    YOU solved my problems =D

  7. Thomas

    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

      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

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

  8. Beno Netto

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

    Thanks!

  9. laila

    thanks a lot.
    my Problem is now solved.

    Now I can omplite my job..

    regards

  10. Chris

    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

  11. Neri

    Thanks, useful 😀

  12. Pankaj

    Thanks .. very use full tutorial..

  13. Sudip Samajder

    Thanks a lot. its awesome

  14. Calis

    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

      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;
      }

  15. shoaib

    great code for check box sellection

  16. Pingback: I want to add multiple items to a shopping cart at the same time.

  17. Solar Panels Installer

    it can be by followings:

    $tags = $_POST[‘tags’];

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

  18. Ali

    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”;
    }
    ?>

  19. Graham

    Many thanks – just what I needed!

  20. Pingback: Въпрос за php код

  21. Pingback: Validate checkboxes sent in array | Jisku.com

Leave a Reply

Your email address will not be published.

*