Multiple Select Drop Down Menu in PHP

Multi Drop Down Menu with Items SelectedAs a continuation from my entry PHP State Drop Down Menu – Reusable Code! I’m now going to cover updating the showOptionsDrop() function we created, to allow for multiple ‘active’ or selected items for the case of a multi-select drop down menu like you see in the image to the right.

It’s actually a very easy change. All we really need to do is pass an array as the active variable instead of a singular string value.

I’m going to use a new array of colors to demo this update since it’s a smaller more manageable array. Of course you can use this with any of the state, month or day of the week arrays from the last article.

PHP

<?php
    $colors = array('red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet', 'pink', 'black', 'white', 'silver', 'gold');
?>

Before we could have just one of those items be the selected item, now we’ll choose an array of multiple values to have selected

PHP

<?php
    $chosen = array(3, 6, 2, 7);
?>

Now we just need to help the function recognize not only a multiple value but also still accept the single value passed (for legacy purposes.)

Updating The showOptionsDrop() Function

We need to help the function first decide if the items that need to be selected are being past as a string or array. We’ll use the PHP built in function is_array() for that. If it is an array, we’ll see if that item is in the array, if it is not an array we will see if the item is equal to the string that was passed.

PHP

<?php
    function showOptionsDrop($array, $active, $echo=true){
        $string = '';

        foreach($array as $k => $v){
            if(is_array($active))       # if it's an array
                $s = (in_array($k, $active))? ' selected="selected"' : '';  # treat it like an array
            else                        # otherwise...
                $s = ($active == $k)? ' selected="selected"' : '';          # stick with what we had before with the old function
            $string .= '<option value="'.$k.'"'.$s.'>'.$v.'</option>'."\n";
        }

        if($echo)   echo $string;
        else        return $string;
    }
?>

Working with Multiple Select Fields

Now that we have our function we just need to create our field and pass our arrays:

The important thing with the form is to remember that in order to show multiple values you must set the size="" attribute in the <select> tag, and to allow multiple values to be selected you must add the multiple="multiple" attribute to the <select>.

{googlead}

Also, when you are passing multiple values through a form when you name your field you will need to append [] to the name of the field to ensure you can collect all of your data in the script that processes the form after it has been submitted. So my select field which I may have defined with name="colors" before now must be name="colors[]" so the processing script recognizes colors as an array of values not one value for colors overwriting another, overwriting another.

<form name="colorform" action="" method="post">
    <select name="colors[]" multiple="multiple" size="15">
        <?php echo showOptionsDrop($colors, $chosen, true); ?>
    </select><br />
    <input type="submit" name="submit" value="submit" />
</form>

Putting it all Together

So now we’ll put it all together for ya, a quick snippet for receiving the form data, or using the predefined chosen colors and outputting the whole thing. A fully functional PHP script.

PHP & HTML

<?php
    if(!isset($_POST['submit']))        # If this form has not been submitted
        $chosen = array(3, 6, 2, 7);    # Use the default
    else                                # Otherwise
        $chosen = $_POST['colors'];     # Use what has been submitted

    function showOptionsDrop($array, $active, $echo=true){
        $string = '';

        foreach($array as $k => $v){
            if(is_array($active))
                $s = (in_array($k, $active))? ' selected="selected"' : '';
            else
                $s = ($active == $k)? ' selected="selected"' : '';
            $string .= '<option value="'.$k.'"'.$s.'>'.$v.'</option>'."\n";
        }

        if($echo)   echo $string;
        else        return $string;
    }

    $colors = array('red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet', 'pink', 'black', 'white', 'silver', 'gold');

?>
<form name="colorform" action="" method="post">
    <select name="colors[]" multiple="multiple" size="15">
        <?php echo showOptionsDrop($colors, $chosen, true); ?>
    </select><br />
    <input type="submit" name="submit" value="submit" />
</form>

Fabulous isn’t it!

This site runs on the Thesis WordPress Theme

Thesis Theme thumbnail

If you're someone who doesn't understand a lot of PHP, HTML, or CSS, Thesis will give you a ton of functionality without having to alter any code. For the advanced, Thesis has incredible customization possibilities via extensive hooks and filters. And with so many design options, you can use the template over and over and never have it look like the same site.

If you're more familiar with how websites work, you can use the fantastic Thesis User's Guide and world-class support forums to make more professional customizations than you ever thought possible. The theme is not only highly customizable, but it allows me to build sites with a much more targeted focus on monetization than ever before. You can find out more about Thesis below:

{ 19 comments }

1 Modboy June 15, 2008 at 1:17 pm

Thx this is pretty useful stuff ;)

2 Krishan Rodrigo July 20, 2008 at 8:42 pm

Very useful. Thanks

3 Weston Doyle December 7, 2008 at 5:26 pm

Multiple selection is a nice feature. Thanks for explaining.

4 Vernon de Goede April 30, 2009 at 8:48 am

Thanks for this. It helped me pretty much out of some problems :)

Thanks!

5 Goldmünzen May 15, 2009 at 5:42 am

Very useful feature. I appreciate it. Thank you

6 Richard July 6, 2009 at 2:40 pm

Having a problem, and this looks like it could solve it with some tweaking.

I’m trying to do an insert into mysql from a multiple select. I want to pass all the values that are selected into the insert, then when the user reviews the form later, all their values are highlighted again?

7 Nazar July 30, 2009 at 6:10 am

it’s very good but iwant to ask you how can insert the multiple value in the database (for example
if Ihave employee work in many project and Iwant to insert three kind of project to one employee)how can Ido that

8 Barry Robinson January 14, 2011 at 5:09 pm

Hi Terry,
I read your article on Multiple Select Drop Down Menu in PHP and I found it
very useful. I was wondering if there is some way to determine the order of clicks,
i.e. if the order in which the user clicks the items in the list is significant,
is there some way for PHP to determine this order and present the
selection to the user in the order selected and not in the order they appear in the menu.
Thanks for your help.

9 Terri Ann
Twitter:
January 14, 2011 at 7:29 pm

I do not believe there’s a way with PHP to handle that without some additional JavaScript work. When the values get passed I believe the are passed int he order in which they appear. To save the order they are selected you’d want to create some JavaScript to handle the changes of selection/deselection and keep those values in a hidden field that also gets passed.
Or if you have JavaScript reorder the elements based as they are clicked – and keep them in order that way – the values would then get passed to the PHP layer in order.

10 Neil February 10, 2011 at 9:05 am

Hi Terri
I’m quite new to all this and the above is very useful as I’ve only just learned how to use drop down menus. Would you by any chance know how it’s possible to add an “any” option to drop down menus, so that if you have a combination of, say, three drop down menus as search criteria it would choose results that match “any” of the variables in one of the menus. Any help or pointing me in the right direction greatly appreciated.
Thanks
Neil

11 Ashok nkumar April 13, 2011 at 4:29 am

Very useful. Thanks

12 Ashok kumar April 13, 2011 at 4:31 am

Hi,

Very useful.
Thanks

13 james mergenthaler April 14, 2011 at 12:30 pm

nice – thanks so much. Who knew a select box could be extended so nicely with the multiple attribute and the [] to tell it to send an array and not a single variable….brilliant!

14 Josh May 18, 2011 at 3:56 pm

Thank you very much! :)

15 mayuri ghogre August 11, 2011 at 3:23 am

thanx

16 Web Hosting October 25, 2011 at 3:02 pm

It is an impressive menu can be done with this code. Looks will make every web site to be very modern and fresh.

17 Manoj February 17, 2012 at 5:17 am

that it’s very useful…

18 aarthi February 18, 2012 at 4:35 am

Very useful!

19 Gary March 2, 2012 at 12:12 pm

Nice. Thanks.

Comments on this entry are closed.

Previous post:

Next post: