How to Handle Form Checkboxes With Same Name in PHP

checkbox_seriesI was working today on a school registration form and I had to process multiple checkboxes with same name with PHP. I share my method below.

The HTML Form (form.html)

The HTML code generates a form with 7 checkboxes. The most important aspect of the form is the name of the checkboxes, which in this cased is ethn[]. The square brackets [] after the name ethn is what creates an array variable for PHP processing.

[html]

<form action=”process.php” method=”post” name=”form1″>
<p>Check all applicable:</p>
<input type=”checkbox” name=”ethn[]” value=”Nonresident Alien” />
Nonresident Alien
<input type=”checkbox” name=”ethn[]” value=”Black, non-Hispanic” />
Black, non-Hispanic
<input type=”checkbox” name=”ethn[]” value=”Asian/Pacific Islander” />
Asian/Pacific Islander
<input type=”checkbox” name=”ethn[]” value=”Hispanic” />
Hispanic <input type=”checkbox” name=”ethn[]” value=”American Indian/Alaskan Native” />
American Indian/Alaskan Native
<input type=”checkbox” name=”ethn[]” value=”White, Non-Hispani” />
White, Non-Hispanic
<input type=”checkbox” name=”ethn[]” value=”Race/ethnicity unknown” />
Race/ethnicity Unknown
<input type=”submit” name=”submit” value=”Submit” />
</form>

[/html]

The PHP Processing Code (process.php)

In the PHP code, we reset the array variable $ethn and we loop through its content, while storing the value of the various array compartments in the  variable $fString. The last line displays the concatenated values of the boxes that have been checked on the form.

[php]

<?php
if(isset($_POST[‘submit’]) and count($_POST[‘ethn’]>0))
{
$ethn=$_POST[‘ethn’];
reset($ethn);
$fString=””;
foreach ($ethn as $key => $value) { $fString=$value.’, ‘.$fString;}
echo $fString;
}
?>

[/php]

That was easy 🙂 You can download the two files.

News Reporter
Lionnel Yamentou Ndzogoue is a young African dreamer, with the vision of creating 10,000 or more jobs in Africa by 2035 in contribution to wealth creation on the continent. This blog is a platform for expressing his thoughts on the world, technology, personal development and other subjects as they come to mind. Some content is republished from other online sources.