PHP State Drop Down Menu – Reusable Code!

In an effort to stop writing and re-writing code I’m going to start sharing some of my favorite functions that I use at home and at work.

I need to create a lot of drop down menus (or select boxes) for CMS’ as well as lead gen forms and registration forms.

I work with one concise PHP USA states array. Everything is on one line to save space, which when it comes to obvious things that won’t be edited often (like states, months, days of the week arrays) is perfect.

My Three Most Common PHP Arrays

PHP USA States Array

The states array uses the all capital version of the state’s abbreviation as the key in this associative array.

PHP

<?php
    $states_arr = array('AL'=>"Alabama",'AK'=>"Alaska",'AZ'=>"Arizona",'AR'=>"Arkansas",'CA'=>"California",'CO'=>"Colorado",'CT'=>"Connecticut",'DE'=>"Delaware",'DC'=>"District Of Columbia",'FL'=>"Florida",'GA'=>"Georgia",'HI'=>"Hawaii",'ID'=>"Idaho",'IL'=>"Illinois", 'IN'=>"Indiana", 'IA'=>"Iowa",  'KS'=>"Kansas",'KY'=>"Kentucky",'LA'=>"Louisiana",'ME'=>"Maine",'MD'=>"Maryland", 'MA'=>"Massachusetts",'MI'=>"Michigan",'MN'=>"Minnesota",'MS'=>"Mississippi",'MO'=>"Missouri",'MT'=>"Montana",'NE'=>"Nebraska",'NV'=>"Nevada",'NH'=>"New Hampshire",'NJ'=>"New Jersey",'NM'=>"New Mexico",'NY'=>"New York",'NC'=>"North Carolina",'ND'=>"North Dakota",'OH'=>"Ohio",'OK'=>"Oklahoma", 'OR'=>"Oregon",'PA'=>"Pennsylvania",'RI'=>"Rhode Island",'SC'=>"South Carolina",'SD'=>"South Dakota",'TN'=>"Tennessee",'TX'=>"Texas",'UT'=>"Utah",'VT'=>"Vermont",'VA'=>"Virginia",'WA'=>"Washington",'WV'=>"West Virginia",'WI'=>"Wisconsin",'WY'=>"Wyoming");
?>

PHP Months Array

There’s more than two ways to represent the English versions of the months of a Gregorian calendar.

For January there’s:

  • January
  • Jan
  • 1

So for the most reusable code we need to incorporate all of those versions. Since we will most likely key off of the numeric value of the month we’ll use that as our key.

PHP

<?php
    $month_arr = array(1=>array('Jan','January'),2=>array('Feb','February'),3=>array('Mar','March'),4=>array('Apr','April'),5=>array('May','May'),6=>array('June','June'),7=>array('July','July'),8=>array('Aug','August'),9=>array('Sept','September'),10=>array('Oct','October'),11=>array('Nov','November'),12=>array('Dec','December'));
?>

Not that in this example I stuck with the common ‘shortened’ versions. Later I’ll show you how to only use the first three characters (the shorter abbreviation) without changing the array, making it super reusable.

PHP Day of the Week Array

Days of the week is another one where you ought to use both a numeric value as well as an abbreviation and a full version of the name, much like months.

PHP

<?php
    $weekday_arr = array(0=>array('Sun','Sunday'),1=>array('Mon','Monday'),2=>array('Tues','Tuesday'),3=>array('Wed','Wednesday'),4=>array('Thurs','Thursday'),5=>array('Fri','Friday'),6=>array('Sat','Saturday'));
?>

Not that in this example I stuck with the common ‘shortened’ versions. Later I’ll show you how to only use the first three characters (the shorter abbreviation) without changing the array, making it super reusable.

Making Drop Down Menu’s with an Array in PHP

Now that we have out common array’s all neat and tidy we’ll create a simple function ot loop through them and create a <select> menu out of ‘em.

This should do the job:

PHP

<?php
    function showOptionsDrop($array){
        $string = '';
        foreach($array as $k => $v){
            $string .= '<option value="'.$k.'"'.$s.'>'.$v.'</option>'."\n";
        }
        return $string;
    }
?>

Simply use this snippet to display a menu of months where the option will be formatted much like <option value="AL">Alabama</option>

HTML/PHP

<select name="states">
    <option value="0">Choose a state</option>
    <?php echo showOptionsDrop($states_arr); ?>
</select>

Now keep in mind this works great for the simple key=>value pairs in the states array, but not yet for the more complex, multi-dimensional array for months and days of the week.

{googlead}

Let’s make that function more advanced before we start working with the multi-dimensional arrays. We need this function to also add the select="select" attribute if that is the item that needs to be selected. This way we can predefine a drop down. this is perfect for server side validation, editing existing content in a CMS as well as setting a date in a drop down menu when the page is loading.

Another parameter I am now in the habit of adding as an optional parameter to my functions is a boolean decision to either echo or return the values.

PHP & HTML

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

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

        if($echo)   echo $string;
        else        return $string;
    }
?>
<select name="states">
    <option value="0">Choose a state</option>
    <?php showOptionsDrop($states_arr, null, true); ?>
</select>

Continue on to page 2: using intermediary functions for the multidimentional array drop down menus

Pages: 1 2

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:

{ 17 comments }

1 PEBCAT June 3, 2008 at 12:45 pm

Nice code. Your formatting could use some work though.

2 Modboy June 15, 2008 at 1:23 pm

Ya interesting ;)

3 Mark November 1, 2008 at 10:19 pm

Thanks for the arrays.

m

4 sivagami March 16, 2009 at 3:08 am

how i submit my dateof birth into table in mysql.
i am using function for to select date through dropdown box.

i have to combine this three field drop down seleted date month year into table. please reply me. i use this following coding but it doesn’t work. anybosdy reply me.

5 Sara May 26, 2009 at 7:34 pm

Thanks for the arrays…just an FYI that your states array was not in alphabetical order. Here is the updated array in the right order:

$states_arr = array('AK'=>"Alaska",'AL'=>"Alabama",'AR'=>"Arkansas",'AZ'=>"Arizona",'CA'=>"California",'CO'=>"Colorado",'CT'=>"Connecticut",'DC'=>"District Of Columbia",'DE'=>"Delaware",'FL'=>"Florida",'GA'=>"Georgia",'HI'=>"Hawaii",'IA'=>"Iowa",'ID'=>"Idaho",'IL'=>"Illinois", 'IN'=>"Indiana",'KS'=>"Kansas",'KY'=>"Kentucky",'LA'=>"Louisiana",'MA'=>"Massachusetts",'MD'=>"Maryland",'ME'=>"Maine",'MI'=>"Michigan",'MN'=>"Minnesota",'MO'=>"Missouri",'MS'=>"Mississippi",'MT'=>"Montana",'NC'=>"North Carolina",'ND'=>"North Dakota",'NE'=>"Nebraska",'NH'=>"New Hampshire",'NJ'=>"New Jersey",'NM'=>"New Mexico",'NV'=>"Nevada",'NY'=>"New York",'OH'=>"Ohio",'OK'=>"Oklahoma", 'OR'=>"Oregon",'PA'=>"Pennsylvania",'RI'=>"Rhode Island",'SC'=>"South Carolina",'SD'=>"South Dakota",'TN'=>"Tennessee",'TX'=>"Texas",'UT'=>"Utah",'VA'=>"Virginia",'VT'=>"Vermont",'WA'=>"Washington",'WI'=>"Wisconsin",'WV'=>"West Virginia",'WY'=>"Wyoming");
6 Brian June 7, 2009 at 9:56 pm

cool.. this will save me time. thanks.

7 Daniel August 25, 2009 at 12:09 pm

Thanks again, nice to find a quick help via Google.

@Sara, your array is in alphabetical order by state code, the posted array code is in alphabetical order by actual state name… so it depends on which part you display to as to which one you should use.

8 Peter June 29, 2010 at 3:40 am

I’m pretty lazy, and I don’t like to have to think, so I just threw this together… works like a charm. Simple “for” loop to select a state from an array…

$state = 'CA'; // the abbreviation is submitted with the form, not the full name

$states = Array('AL - Alabama', 'AK - Alaska', 'AZ - Arizona', 'AR - Arkansas', 'CA - California', 'CO - Colorado', 'CT - Connecticut', 'DE - Delaware', 'DC - District Of Columbia', 'FL - Florida', 'GA - Georgia', 'HI - Hawaii', 'ID - Idaho', 'IL - Illinois', 'IN - Indiana', 'IA - Iowa', 'KS - Kansas', 'KY - Kentucky', 'LA - Louisiana', 'ME - Maine', 'MD - Maryland', 'MA - Massachusetts', 'MI - Michigan', 'MN - Minnesota', 'MS - Mississippi', 'MO - Missouri', 'MT - Montana', 'NE - Nebraska', 'NV - Nevada', 'NH - New Hampshire', 'NJ - New Jersey', 'NM - New Mexico', 'NY - New York', 'NC - North Carolina', 'ND - North Dakota', 'OH - Ohio', 'OK - Oklahoma', 'OR - Oregon', 'PA - Pennsylvania', 'RI - Rhode Island', 'SC - South Carolina', 'SD - South Dakota', 'TN - Tennessee', 'TX - Texas', 'UT - Utah', 'VT - Vermont', 'VA - Virginia', 'WA - Washington', 'WV - West Virginia', 'WI - Wisconsin', 'WY - Wyoming');

$selected = '';
for ($s=0;$s<=50;$s++){ // let's not forget DC
    if ($state == $states[$s]){
        $selected = ' selected="selected"';
    } else {
        $selected = '';
    }
    $st = substr($states[$s], 0, 2);
    echo '' . $states[$s] . '';
}
9 Larry Zoumas August 17, 2010 at 3:50 am

Nice code Peter, you rock.

10 Preeti August 19, 2010 at 7:39 am

can anybody give me the detail code in php
after selecting item from dropdown it will display all related information from table i.e. present database.

11 John October 12, 2010 at 4:09 pm

Hi – i would like to implement the US States dropdown on my WP Blog (btw, I have Thesis theme).
Your info above is useful to an extent – but how do you actually implement this code, where do you put the code, i.e. what file(s) do i put all these snippets of code into? And do i need to setup a new mysql database in cpanel as well – i don’t quite understand – people’s comments above are confusing me. (obviously i’m not a coder, but if i have clear instructions i can follow them easily).

12 Don February 3, 2011 at 4:01 am

Here’s a little more functional version…

<?php
$state = 'CA';
$states = Array('AL - Alabama', 'AK - Alaska', 'AZ - Arizona', 'AR - Arkansas', 'CA - California', 'CO - Colorado', 'CT - Connecticut', 'DE - Delaware', 'DC - District Of Columbia', 'FL - Florida', 'GA - Georgia', 'HI - Hawaii', 'ID - Idaho', 'IL - Illinois', 'IN - Indiana', 'IA - Iowa', 'KS - Kansas', 'KY - Kentucky', 'LA - Louisiana', 'ME - Maine', 'MD - Maryland', 'MA - Massachusetts', 'MI - Michigan', 'MN - Minnesota', 'MS - Mississippi', 'MO - Missouri', 'MT - Montana', 'NE - Nebraska', 'NV - Nevada', 'NH - New Hampshire', 'NJ - New Jersey', 'NM - New Mexico', 'NY - New York', 'NC - North Carolina', 'ND - North Dakota', 'OH - Ohio', 'OK - Oklahoma', 'OR - Oregon', 'PA - Pennsylvania', 'RI - Rhode Island', 'SC - South Carolina', 'SD - South Dakota', 'TN - Tennessee', 'TX - Texas', 'UT - Utah', 'VT - Vermont', 'VA - Virginia', 'WA - Washington', 'WV - West Virginia', 'WI - Wisconsin', 'WY - Wyoming');
?>
- select -
<?php
        $selected = &#039;&#039;;
        for ($s=0;$s&lt;=50;$s++)
        { 
            //get abbreviation string
            $stAbbr = substr($states[$s], 0, 2);
            //get string length
            $stringLength = strlen($states[$s]);
            //get state display name
            $stName = substr($states[$s], 4, $stringLength);
            if ($state == $stAbbr)
            {
                $selected = &#039; selected=&quot;selected&quot;&#039;;
            }
            else
            {
                $selected = &#039;&#039;;
            }
           echo '&amp;lt;option value="'.$stAbbr.'" ' .$selected.'&amp;gt;'.trim($stName) .'&amp;lt;/option&amp;gt;';
}
?>
13 Terri Ann
Twitter:
February 7, 2011 at 6:56 pm

Thanks everyone for contributing your code to the thread of comments but I think some of you are missing the original concept of the post – the code I provided was highly portable and could easily be applied to many different arrays, types of arrays and in tons of different use cases. It’s not that the code in the original post is any more or less usable it’s a matter of portability of code and efficient use of design patterns when working with arrays of data.

Cheers and continue to add your code!

14 Bethany April 26, 2011 at 12:16 pm

Your array alphabetizes the state code. The poster’s array alphabetizes the actual state. (Alabama comes before Alaska.)

15 gh,l September 19, 2011 at 2:01 am

murkh

16 Erin October 12, 2011 at 9:22 pm

I implemented your code on our site and it rocks! Thanks!

One question: I’m using it as the first dropdown (states). Once user selects it, it fills in a second dropdown from a database of clients in that state. It all works fine except:

The check for what state is selected doesn’t work. It always shows “Select state”. Any ideas?

Thanks again!

17 nicorellius March 13, 2012 at 2:34 pm

Thanks a billion for this – in a pinch, I found this code and it worked like a dream. I appreciate your post!

Comments on this entry are closed.

{ 2 trackbacks }

Previous post:

Next post: