Tuesday, March 31, 2009

Read values from Checkbox in PHP

In php chekboxes are referred as arrays. When ever we read the values from the checkbox all the values are retrieved as the array. From the form if we read the value of textbox or a radio button or the select box, we generally read by using the name of the tab. For example if we read the value of the textbox then we directly read as $_POST['textboxname'].

But when reading the values from the checkboxes we need to be very carefull. As the checkbox value comes in the form of array. First we need to read the array and then split the array and read the values.

Example:

<form action="test.php" method="post">
<input type="checkbox" name="test[]" value="1">
<input type="checkbox" name="test[]" value="1">
<input type="checkbox" name="test[]" value="1">
<input type="checkbox" name="test[]" value="1">
<input type="checkbox" name="test[]" value="1">
<input type="checkbox" name="test[]" value="1">
<input type="submit" value="submit">
</form>

Code for reading the checkbox values.

$test=$_POST['test'];
$finalvalues="";
if($test!="")
{
foreach($test as $cat4)
{
if($finalvalues=="")
{
$finalvalues=$cat4;
}
else
{
$finalvalues=$finalvalues."#".$cat4;
}
}
}

Here the final values are stored in the variable $finalvalues seperated by the "#" character. here we used foreach to read the values which are selected by the user individually.

0 comments:

Post a Comment