Parsing multiple checkbox forms with php

Tutorials for php.

Parsing multiple checkbox forms with php

Postby Mortisimus on Mon Aug 25, 2008 8:56 pm

Ok, in this tutorial I will show you how to create a script that will parse multiple checkboxes from a form.

Now, create a new page, this can be called anything. Put the following html code in the page to display the form.

Code: Select all
<form action="parse.php" method="post">
<input type="checkbox" name="person[]" value="Tom" /> Tom<br />
<input type="checkbox" name="person[]" value="James" /> James<br />
<input type="checkbox" name="person[]" value="Robert" /> Robert<br />
<input type="submit" name="submit" value="Submit" />
</form>


The name is set to person[] so all these checkboxes values can be parsed in the same variable as an array. The action of the form is set to parse.php so now we will create that file.

parse.php
Code: Select all
if(isset($_POST['submit'])){
    // the form has been submitted
    $person = $_POST['person'];
   
    print_r($person);
}
else
{
    // the form hasn't been submitted
    echo "Please go back and fill in the form!";
}


Ok, this is very simple. Firstly, we check if the form has been submitted by seeing if the $_POST['submit'] has been set. Then to make it more easy to use, we assign the submitted array of selected checkboxes to a variable, $person. Then purely for debugging reasons, we do a print_r of the array to see what values are in the form.

Just for another example, I will show you how you can echo all submitted values in the array. All you need is a very simple foreach
Code: Select all
foreach($person as $p){
    echo $p;
}


Thank you for reading. ;)
User avatar
Mortisimus
Site Admin
 
Posts: 21
Joined: Mon Aug 25, 2008 6:04 pm

Return to PHP Tutorials

Who is online

Users browsing this forum: No registered users and 1 guest

cron