PHP Multiple Checkbox Array

Darek Gajda picture Darek Gajda · Dec 25, 2012 · Viewed 261.6k times · Source

I've looked around for a few examples here but a lot of them are either too advanced for my grasp of PHP or their examples are too specific to their own projects. I am currently struggling with a very basic part of a PHP form.

I am trying to create a form with a few checkboxes, each assigned a different value, I want these to be sent to a variable (array?) that I can echo/use later, in my case I will be sending the checked values in an email.

So far, I have tried a few variations, but the closest I have come to it is this...

<form method='post' id='userform' action='thisform.php'>
<tr>
    <td>Trouble Type</td>
    <td>
    <input type='checkbox' name='checkboxvar' value='Option One'>1<br>
    <input type='checkbox' name='checkboxvar' value='Option Two'>2<br>
    <input type='checkbox' name='checkboxvar' value='Option Three'>3
    </td>
</tr>
</table>
<input type='submit' class='buttons'>
</form>

<?php
$checkboxvar[] = $_REQUEST['checkboxvar'];
?>

Where I'd echo $checkboxvar[] into my email. Am I going about this completely wrong? The other idea I had was to use a lot of if statements.

Answer

cryptic ツ picture cryptic ツ · Dec 25, 2012
<form method='post' id='userform' action='thisform.php'> <tr>
    <td>Trouble Type</td>
    <td>
    <input type='checkbox' name='checkboxvar[]' value='Option One'>1<br>
    <input type='checkbox' name='checkboxvar[]' value='Option Two'>2<br>
    <input type='checkbox' name='checkboxvar[]' value='Option Three'>3
    </td> </tr> </table> <input type='submit' class='buttons'> </form>

<?php 
if (isset($_POST['checkboxvar'])) 
{
    print_r($_POST['checkboxvar']); 
}
?>

You pass the form name as an array and then you can access all checked boxes using the var itself which would then be an array.

To echo checked options into your email you would then do this:

echo implode(',', $_POST['checkboxvar']); // change the comma to whatever separator you want

Please keep in mind you should always sanitize your input as needed.

For the record, official docs on this exist: http://php.net/manual/en/faq.html.php#faq.html.arrays