PHP State Drop Down Menu – Reusable Code!

by Terri Ann on January 3, 2008

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

{ 10 comments… read them below or add one }

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.

Leave a Comment

{ 2 trackbacks }

Previous post:

Next post: