Using Form Input Arrays For Checkboxes

By  on  

One way that I've gotten faster at XHTML forms is using input arrays whenever possible. Input arrays allow me to deal with just one variable for checkboxes that serve as multiple answers to one question. Here's how the process works.

Step 1: The XHTML Form

<table cellpadding="0" cellspacing="2">
	<tr>
		<td><input type="checkbox" name="how_hear[]" id="how_hear1" value="Website" <?php echo in_array('Website',$how_hear) ? 'checked="checked"' : ''; ?> /></td>
		<td style="padding-left:3px"><label for="how_hear1">Website</label></td>
	</tr>
	<tr>
		<td><input type="checkbox" name="how_hear[]" id="how_hear2" value="TV Commercial" <?php echo in_array('TV Commercial',$how_hear) ? 'checked="checked"' : ''; ?> /></td>
		<td style="padding-left:3px"><label for="how_hear2">TV Commercial</label></td>
	</tr>
	<tr>
		<td><input type="checkbox" name="how_hear[]" id="how_hear3" value="Magazine Ad" <?php echo in_array('Magazine Ad',$how_hear) ? 'checked="checked"' : ''; ?> /></td>
		<td style="padding-left:3px"><label for="how_hear3">Magazine Ad</label></td>
	</tr>
	<tr>
		<td><input type="checkbox" name="how_hear[]" id="how_hear4" value="Billboard" <?php echo in_array('Billboard',$how_hear) ? 'checked="checked"' : ''; ?> /></td>
		<td style="padding-left:3px"><label for="how_hear4">Billboard</label></td>
	</tr>
	<tr>
		<td><input type="checkbox" name="how_hear[]" id="how_hear5" value="Other" <?php echo in_array('Other',$how_hear) ? 'checked="checked"' : ''; ?> /></td>
		<td style="padding-left:3px"><label for="how_hear5">Other</label></td>
	</tr>
</table>

Note that the name attribute of each input is the same: how_hear[]. The brackets indicate that the input field is an array. Also note the PHP in each input tag that determines if the chechbox should checked initially.

Step 2: The PHP Form Validation and Processing

//initialize
$how_hear = count($_POST['how_hear']) ? $_POST['how_hear'] : array();

//echo out their choices separated by a comma
echo count($how_hear) ? implode(', ',$how_hear) : 'Nothing';

To avoid PHP warnings, we declare the $how_hear array at the very top.

PHP's count() function returns the number of items selected, so we you require at least one be checked, count() is what we'll use.

Lastly, to display the selections as a list, we use the implode() function.

That's it! Click here to see an example.

Recent Features

  • By
    Interview with a Pornhub Web Developer

    Regardless of your stance on pornography, it would be impossible to deny the massive impact the adult website industry has had on pushing the web forward. From pushing the browser's video limits to pushing ads through WebSocket so ad blockers don't detect them, you have...

  • By
    39 Shirts &#8211; Leaving Mozilla

    In 2001 I had just graduated from a small town high school and headed off to a small town college. I found myself in the quaint computer lab where the substandard computers featured two browsers: Internet Explorer and Mozilla. It was this lab where I fell...

Incredible Demos

  • By
    Fade Images with MooTools LazyLoad

    I recently received an email from a MooTools developer asking a great question about my LazyLoad class: "I'm using your LazyLoad MooTools plugin (which is great, by the way). I have been trying to figure out how to modify it so that once an image scrolls into...

  • By
    Create a 3D Panorama Image with A-Frame

    In the five years I've been at Mozilla I've seen some awesome projects.  Some of them very popular, some of them very niche, but none of them has inspired me the way the MozVR team's work with WebVR and A-Frame project have. A-Frame is a community project...

Discussion

  1. I didn’t test yet but makes sense… It surely will help retrieving data from checkboxes (what was always trouble)…

    And I’m amazed how often you publish articles Dave, congrats =) I’m very happy I could find your blog and it’s been very helpful!

  2. Great tips !
    I use this method for “Delete” :

    for ($i = 0; $i < count($_POST['delete']); $i++) {
    $requete = mysql_query("DELETE FROM table
    WHERE id='".$_POST['delete'][$i]."'");
    }
  3. Catar4x OUCH! you know that this is vulnerable to sql injection? Never put request params into sql like that without escaping them for ‘, ; and ” otherwise someone could create a form which would post this.. 1′;drop table; select * from table where id=’
    mysql would execute three statements…

    DELETE FROM table WHERE id=’1′;

    drop table table;

    select * from table where id=$_POST[‘delete’][$i]

  4. didier

    how about xhtml validation?
    I’ve been using the [ ] brakets to pass arrays to php but this won’t validate as xhtml.

  5. Was quite simple, but this article saved a day of repeated stupid mistakes, thank you.

  6. dwargo

    name=”how_hear[]”… I’m in shock… How didn’t I know this?

    Thank you, you just saved me rewriting my class from scratch!

  7. It is called a ternary operator it is short hand for an if statement
    (if this is true)? do this : else do this

  8. pim

    @didier this is not true, the square brackets validate perfectly (I just checked). XHTML expects inputs to be enclosed in a fieldset tag though.

  9. Daniel

    Does this array technique work with other types of inputs as well?

  10. Nsaji

    it works with other inputs as well. i just tried it

  11. Staffan

    Is it possible to make the echo to INPUT INTO a table instead?
    I just don’t understand how.

    I want the fields to end up in a table on separate lines instead.
    So, that how_hear is in a table where I will also have the user.
    So on each line I want the how_hear and next to that the user_id.
    If they check more than one checkbox, I want it to add those fields as separate inputs.

    Since I am planning to use it as genre for music. So the user can check more than one genre for a song.

  12. rafaCode

    Do not use this technique if what you expect at any point, to be able to use jquery validation on your fields.

    http://stackoverflow.com/questions/19282526/validation-of-fields-with-same-name-and-class-get-typeerror-e-validator-method

  13. mdla

    Thank You veeeeeeeeeery much! You saved my life! I was looking the way to get the values of my selected checkboxes for about 2 days. It works perfectly for me in Laravel with the corresponding changes.
    If someone else need it, check the code below:

    //initialize
    $how_hear = count(Input::has('how_hear')) ? Input::get('how_hear'): array();
    
    //pass the var that contain the choices separated by a comma, to the Blade Template as correspond.
    
    $checkboxes= count($how_hear) ? implode(', ',$how_hear) : 'Nothing';
    
  14. Mladen

    Thanks!
    Is this option added in html5?

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!