fm_build_select()

This is a small function for an UI Toolkit. It builds an select list of an associative array.


Code

<?php

// ================================================================
// string fm_build_select(string $name, array $options,
//                        [mixed $selected])
//
// Build an HTML <select> statement with options from the assoc.
// array $options (value => caption) and the option defined by
// $selected (must be a key or an array of keys in the $options
// array) marked as selected. Returns the resulting HTML code or
// FALSE on error.

function fm_build_select($name, $options, $selected = '') {
    if (
$selected == '') $selected = key($options);
    if (!
is_array($selected)) {
        
$selected = array($selected);
        
$select = "<select name=\"$name\">\n";
    } else {
        
$select = "<select name=\"$name" . "[]\" multiple>\n";
    }

    foreach (
$options as $value => $caption) {
        
$select .= "   <option value=\"$value\"" .
          (
in_array($value, $selected) ? " selected" : "") .
          
">$caption</option>\n";
    }
    
$select .= "</select>\n";
    return
$select;
}

?>