Get Multiple Checkbox Values in PHP

I know most of the developers already know it as its simple and easy but still it’s a little bit challenging when new developers encounter such situations in their projects. I also received this as a tutorial request from a guy who has to implement this in his college project. He needs to get multiple checkbox values through a form and store them. As it’s simple and quick so I thought to publish this tutorial as a quick tip. I have written about how to select deselect checkboxes using jQuery you can have a look at that. If you want to get value of a single checkbox then it’s as easy as receiving value of any other normal variable type. The trick comes when you need to capture multiple values from checkboxes. Let’s see how easy it is and you can understand this easily.

multiple checkbox php

                                            Live Demo

Lets take a look at how we handle multiple checkboxes in PHP. We use Array instead of a normal variable to retrieve values. To store all the hobbies checked by user I have used hobbies[] array.

Code for form in index.html:

<form action="checkbox.php" method="post">
 <label class="head">Select Your Hobbies:</label><br/><br/>
 <input type="checkbox" name="hobbies[]" value="Playing"><label>Playing</label><br/>
 <input type="checkbox" name="hobbies[]" value="Coding"><label>Coding.</label><br/>
 <input type="checkbox" name="hobbies[]" value="Reading"><label>Reading</label><br/>
 <input type="checkbox" name="hobbies[]" value="Hacking"><label>Hacking</label><br/>
 <input type="checkbox" name="hobbies[]" value="Sleeping"><label>Sleeping</label><br/><br/>
 <input type="submit" name="submit" Value="Submit"/>


In Checkbox.php file we process this array using a foreach loop so that we can retrieve all the values successfully.

Code for checkbox.php:

 if(!empty($_POST['hobbies'])) {

 //Loop through hobbies array to fetch individual hobby so that we can use them
 echo "<h2> You have selected: </h2>";
 foreach($_POST['hobbies'] as $hobby) {
 echo "<p>".$hobby ."</p>"; //Print all the hobbies

/* Alert hobbies using JS
$show = "<p>".$hobby ."</p>";
echo "<script type='text/javascript'>alert(\"Your Hobbies are: '$show'\");</script>";

 echo "<b>Please Select at least One Hobby.</b>";

The html form when structured in PHP Post/get array:

 [hobbies] => Array
 [0] => Playing
 [1] => Coding
 [2] => Reading
 [3] => Hacking
 [4] => Sleeping

 [submit] => Submit

This is a simple tutorial but I know its going to help a lot of new developers. Please share this simple tutorial with your friends and followers. Let me know if you have any questions or if you just want to say “Hi” comment below 🙂

About sanjeev

Dreamer, Blogger and Thinker. I love to help people in solving their problems. You can also join me HERE

Related posts:

4 Responses so far.

  1. actually i need to write more data in msword file from data base in php
    tell me code about this

Comments are closed.