View Full Version : assigning default select tag

07-20-2007, 12:31 AM
I have a config file editor page that should read the config file, then automatically select a <option> from a <select> tag. I dont want to have to write an if-else statement for each line in the config file(there are over 200)
and I came up with 2 ways to do this and was wondering which would be easier and less cpu intensive.
1) Create a loop for each config option, and check on each step in the loop for what should be 'selected' by default.
2) Make a function to check. EX:
(checkifset prints out selected="selected")

<option other stuff checkifset('config_option','value1'); >Value 1</option>
<option other stuff checkifset('config_option','value2'); >Value 2</option>
<option other stuff checkifset('config_option','value3'); >Value 3</option>

It seems that option 2 would be easier to code(since I already have the html coded out), but it may also be more cpu intensive.

Any thoughts?


07-20-2007, 02:19 AM
I keep my config options in an array (makes it easier to add new options when you remember the bits you forgot ;) or add new functionality.

the below is just an example, I keep the actual option building stuff in a function so it can be reused but you get the general idea ?

'imagick_php'=>'Image Magick extension',
'imagick'=>'Image Magick (Exec)',
'gd'=>'GD PHP Extension'
$curr here is the current configuration loaded into an array !
foreach($options['IMAGE_ENGINE'] as $k=>$v){
$sel=(isset($curr['IMAGE_ENGINE']) && $curr['IMAGE_ENGINE']==$k) ? 'selected="SELECTED" ' : '' ;
$IMAGE_ENGINE[]='<option '.$SEL.'value="'.$k.'">'.$v.'</option>';
echo implode("\n", $IMAGE_ENGINE);

07-20-2007, 08:45 AM
Try to use the function below...

you can modify it as well..


/* your SELECT options */
$select_options = array
'config option 1',
'config option 2',
'config option 3'

$selected_item = 'config option 2'; // your SELECTED option in SELECT

echo createSelect($select_options,$selected_item);

/* returns the html SELECT with the selected item
@select_options = (array) select options
@selected_item = the selected item in the options
function createSelect($select_options,$selected_item)
$select = "<select name=\"cmb\">\n";

foreach ($select_options as $option_value => $option_text )
$is_selected = '';

if($option_text == $selected_item)
$is_selected = "selected";

$select .= "<option value=\"".$option_value."\" ".$is_selected.">".$option_text."</option>";

$select .= "<\select>\n";

return $select;