get values of multiple input elements from a form

Posted: February 4, 2007 in next to nothing

have you ever had a riduculously simple problem on how to get the values of, say, multiple checkboxes in a form? getting the value of an element in an HTML form is easy. in fact, it’s the first thing you would learn in web scripting languages such as PHP. (aside from echo “Hello World”)

let’s say for example that your form is dynamically created with many checkboxes for the purpose of letting the user check as many as would require him/her. good if your question has always the same number of answers/options. what if it’s not?

here’s a tip i learned somewhere and it’s very helpful in dealing with this kinds of situations.

say you have an undetermined number of, again, checkboxes. just name it like how you would with arrays, that is with a ‘[]’ in the end. it’s like this:

<input name=”‘CHECKBOX[]'” value=”‘SOME_VALUE'” type=”‘checkbox'”>

then you can also get the values of whatever was checked in the same way that you would an array. just make a loop, like this for example:

$cnt = count( $_POST[‘CHECKBOX’] );
if ( $cnt > 0 ) {
   for ( $x = 0; $x < $cnt; $x++ ) {
      echo $_POST[‘CHECKBOX’][$x];

that’s it! you’re done. of course, you can apply this to something else and not just checkboxes.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s