Wrox Home  
Search P2P Archive for: Go

  Return to Index  

pro_php thread: checkbox value


Message #1 by "Sokun, Chorn" <sokunxp@g...> on Sun, 19 May 2002 10:15:10 +0700
Well, there's two approaches you can take.

My preference is to give all related checkboxes the same name and create an
array to help group the data.

Let's say you had a form that asked a user if they do any board sports
(snow, skate, surf).  Assume the user selects "Surf" and "Snow"


[Arrays]

Version 1:
Do you:
<FORM...>
  <INPUT type="checkbox" name="sports[]" value="snow">Snow</INPUT>
  <INPUT type="checkbox" name="sports[]" value="skate">Skate</INPUT>
  <INPUT type="checkbox" name="sports[]" value="surf">Surf</INPUT>
  <INPUT type="submit">
</FORM>


Submitting this would generate an array, $sports:
  [0] => 'snow'
  [1] => 'surf'

This kind of array is easy to iterate across using numerical indexes.




[Version 2:]

Do you:
<FORM...>
  <INPUT type="checkbox" name="sports[snow]">Snow</INPUT>
  <INPUT type="checkbox" name="sports[skate]">Skate</INPUT>
  <INPUT type="checkbox" name="sports[surf]">Surf</INPUT>
</FORM>

Submitting this would generate an array, $sports:
  [snow] => 'On'
  [surf] => 'On'

This kind of array is easy to iterate across with a foreach.  The difference
being that the key tells you which box was checked, not the value.


You can, of course, use a combination of these array options to suit your
preference.

Also -- don't think that I'm saying "use one array for ALL your checkboxes".
Far from it -- the array approach lets you group together related inputs.
If I had another input on the same form about "Which import beers do you
like?" I would definitely not use name="sports[]" for those inputs.


Best of luck,

nik


  Return to Index