function form_select_options

Converts a select form element's options array into HTML.

Parameters

$element: An associative array containing the properties of the element.

$choices: Mixed: Either an associative array of items to list as choices, or an object with an 'option' member that is an associative array. This parameter is only used internally and should not be passed.

Return value

An HTML string of options for the select form element.

Related topics

1 call to form_select_options()
theme_select in drupal/core/includes/form.inc
Returns HTML for a select form element.

File

drupal/core/includes/form.inc, line 2771
Functions for form and batch generation and processing.

Code

function form_select_options($element, $choices = NULL) {
  if (!isset($choices)) {
    if (empty($element['#options'])) {
      return '';
    }
    $choices = $element['#options'];
  }

  // array_key_exists() accommodates the rare event where $element['#value'] is NULL.
  // isset() fails in this situation.
  $value_valid = isset($element['#value']) || array_key_exists('#value', $element);
  $value_is_array = $value_valid && is_array($element['#value']);
  $options = '';
  foreach ($choices as $key => $choice) {
    if (is_array($choice)) {
      $options .= '<optgroup label="' . $key . '">';
      $options .= form_select_options($element, $choice);
      $options .= '</optgroup>';
    }
    elseif (is_object($choice)) {
      $options .= form_select_options($element, $choice->option);
    }
    else {
      $key = (string) $key;
      if ($value_valid && (!$value_is_array && (string) $element['#value'] === $key || $value_is_array && in_array($key, $element['#value']))) {
        $selected = ' selected="selected"';
      }
      else {
        $selected = '';
      }
      $options .= '<option value="' . check_plain($key) . '"' . $selected . '>' . check_plain($choice) . '</option>';
    }
  }
  return $options;
}