Sunday, September 20, 2009

PHP and checkboxes with the same name

If you have worked with ColdFusion before you know that if have checkboxes in the form that have the same name they come into the form scope as a comma separated list. I tried to pull the same trick using PHP but only go the last checkbox's value. Confused I did a little a research and found out that if you put [] behind your name PHP interprets it as an array but keeps everything to the left of the [] as your name when comeing in through the $_REQUEST scope. See below.

<form name="the_form" method="post">

<input type="checkbox" name="boarder" value="Joe" >
<input type="checkbox" name="boarder" value="Jamie" >
<input type="checkbox" name="boarder" value="Jake" >

</form>

In ColdFusion when you submit this form you would get an variable in the form scope
called "boarder" with the values "Joe,Jamie,Jake" in a comma seperated list. In PHP you would get "Jake". To solve this I added [] to the checkbox name.

<form name="the_form" method="post">

<input type="checkbox" name="boarder[]" value="Joe" >
<input type="checkbox" name="boarder[]" value="Jamie" >
<input type="checkbox" name="boarder[]" value="Jake" >

</form>

Now in PHP you would get an variable in the $_REQUEST scope called "boarder" which is type array with first element "Joe, the second element "Jamie", and the third element "Jake". Notice the variable name is still "boarder" even though we specified "boarder[]".

I am not choosing sides on PHP or ColdFusion they are both cool, but I found it interesting that you can tell PHP what type this var is through the html form.

I found my answer at:
http://www.computing.net/answers/webdevel/php-amp-checkboxes/1122.html#postfp

1 comment:

  1. Very interesting. I wish the default behavior in CF would be to store each checkbox value in an array, but you might be able to get the desired result using the Form Utilities project on RIAForge.

    http://formutils.riaforge.org/

    ReplyDelete