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.
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"/> </form>
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:
The html form when structured in PHP Post/get array:
Array ( [hobbies] => Array (  => Playing  => Coding  => Reading  => Hacking  => 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