Create a function which is passed the array of values and the setting which should be preselected:
PHP Code:
// spoofing your array collected from your db
$arr = array(212=>"GHI", 95=> "DEF");
// the one to preselect to
$chosen = 95 ;
function createSelectList($name, $arr, $chosen_one) {
$html = "<select name='$name'>" . PHP_EOL ;
foreach($arr as $key=>$val){
$selected = ($key === $chosen_one) ? "selected='selected'" : "" ;
$html .= "<option value='$key' $selected>$val</option>" . PHP_EOL ;
}
return $html . "</select>" .PHP_EOL ;
}
echo createSelectList("mylist", $arr, 95);
//<select name='mylist'>
//<option value='212' >GHI</option>
//<option value='95' selected='selected'>DEF</option>
//</select>
You can take this a lot further and build in the sql statement as well, if you were inclined - though some might say this function is then taking on too much responsibility -- but you can make it quite a useful tool.
Bookmarks