How to handle checkbox in PHP

Check box handling is bit different compared to other form objects because it can receive multiple values. Here is the HTML code for the form

1
2
<input name="fruit[]" type="checkbox" value="a" />Apple
<input name="fruit[]" type="checkbox" value="o" />Orange

and PHP code to handle the checkbox values.

1
2
3
4
5
6
7
8
9
 $fruit = $_POST['fruit'];
 if(!empty($fruit))
 {
   foreach($fruit as $value)
   {
     $string = $value.','.$string;
   }
   $value = rtrim($value, ',');
 }

Leave a Reply

Your email address will not be published. Required fields are marked *