faqts : Computers : Programming : Languages : PHP : Common Problems : Forms and User Input : URLs and Post or Get Methods

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

160 of 198 people (81%) answered Yes
Recently 9 of 10 people (90%) answered Yes

Entry

If I make multiple select from SELECT TAG, how can i receive array of variables through POST or GET Methods??

Jan 11th, 2007 03:07
Gustav Bertram, Ben Udall, Guillermo Sobalvarro, Marat Saitov,


Short answer is to append [] to the end of the SELECT tag name.  Each 
option selected will be stored in an array starting at index 0.
Longer explanation:
Say you have a list box like the one below:
    <SELECT name="lights" multiple>
        <OPTION value="red">Red</OPTION>
        <OPTION value="green">Green</OPTION>
        <OPTION value="blue">Blue</OPTION>
    </SELECT>
The user selects Red and Blue, then submits the form.  When PHP tries 
to assign a variable for that form element, each option selected 
overwrites the last one.
    $lights = "red";
    $lights = "blue";
All you would know is blue was selected.  If, instead, the tag name had 
brackets on the end like below:
    <SELECT name="lights[]" multiple>
PHP would create $lights as an array instead of a string.
    $lights[] = "red";
    $lights[] = "blue";
Now, ($lights[0] == "red"), ($lights[1] == "blue"), and you can tell 
which options were selected.
And, to make things simpler for those in a hurry:
$selcount = count($lights);
will store the total number of elements that were selected in variable
$selcount.
To store all selected elements in a single variable use:
$fullvar = implode(" ", $lights);
echo $fullvar;
This will create a single variable ($fullvar) that contains all the
elements selected, separated by a space.  e.g.: red white.  You can then
update your table or whatever with the selected values using one
variable ($fullvar).