PHP – get the check box values of HTML form

Posted by Shek on July 30, 2010 under HTML, PHP | Be the First to Comment | Total View: 3,547 views

Editor’s note: In some cases when you try to create a HTML form for user to input data, you might like to include a set of check boxes for them to input multiple choices, however in order to get the data from a set of check boxes with PHP, I think the easier way is to use array for it, and here in this example I am going to show you how to do so

First we create a HTML form with a set of check boxes, once submitted, the data will pass to test.php:

1
2
3
4
5
6
<form action="test.php" method="post" name="form1" />
<input type="checkbox" name="color[]" value="red" /> red 
<input type="checkbox" name="color[]" value="green" /> green   
<input type="checkbox" name="color[]" value="yellow" /> yellow 
<input type="submit" name="submit" value="submit" />
</form>

red

green

yellow

See the check boxes are in one array color[ ] , now we take a look at the test.php file

First we have to get only the value from boxes which are checked, if condition is used here:

if (isset($_POST['color'])){
.............
}

for all the selected check boxes, we then use a foreach() to loop everyone of them and print it out onto the screen:

1
2
3
4
5
6
7
if (isset($_POST['color'])){
foreach ($_POST['color'] as $value)
{
echo $value;
echo "<br>";
}
}

Not what you want? Try a Search

Add A Comment

*