PHP State Drop Down Menu - Reusable Code!
Intermediary Functions for Multi Dimentional Arrays in Drop Down Menus
Using the multi-dimensional arrays requires an intermediary function (or code snippet, that's up to your needs, I use functions so I can continue to re-use it easily.
So if I want a drop down that looks like <option value="jul">July (7)</option> [...]
I'd manipulate the array to reflect array('jul' => 'July (7)' [...]);
Here's the function that will do that for us, and then pass that new 'temporary' array to the showOptionsDrop function we earlier perfected. We'll only be passing the active value this time and forcing the function to return and calling the array as global within the monthOptionsDrop function.
PHP
<?php
// Note this is the same function as the previous page
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;
}
// Here's our new intermediary function
function monthOptionsDrop($active){
global $month_arr;
foreach($month_arr as $k => $v){
$short = substr( strtolower($v[1]),0,3 ); //lowercase, and pull the first 3 letters NOT the abbreviation
$month_arr_new[$short] = $v[1] . " ($k)";
}
return showOptionsDrop($month_arr_new, $active, false);
}
?>
Which works like a champ like this (which will highlight <option value="mar" selected="selected">March (3)</option>):
HTML/PHP
<select name="months">
<option value="0">Choose a month</option>
<?php echo monthOptionsDrop(3); ?>
</select>
Hope that helped you think about working with PHP arrays and drop down menu's differently. It may not be the best solution but it always works for me (quick and easy too!)
Read more about modifying this code to make it work for drop down menu's that have and can select multiple options.
Multiple Select Drop Down Menu in PHP are an easy modification to this lesson and it's also backwards compatible in case you need to improve the code for your needs at a later time.
the newest discoveries, stories and shared tips!Come on, all the cool kids are doing it ;)




Nice code. Your formatting could use some work though.