form_dropdown()

function form_dropdown(string $name, array $options, string|int|null $selected_key = null, array $attributes = []): string

Description

Generates an HTML select menu (dropdown). Creates a list of options where users can select one or multiple values.

Parameters

ParameterTypeDescription
$namestringThe name attribute for the select element.
$optionsarray<string|int,string>Associative array where keys are option values and values are display text.
$selected_keystring|int|null(optional) The key of the option that should be selected.
$attributesarray(optional) HTML attributes for the select element. Defaults to an empty array ([]).

Return Value

TypeDescription
stringThe generated HTML select menu with options.

Example #1: Basic Dropdown

Example #2: Dropdown with Selected Value

Example #3: Dropdown with Placeholder Option

Example #4: Multiple Selection Dropdown

Notes

  • For multiple select dropdowns, append [] to the field name and pass selected values as an array.
  • Option values and display text are automatically HTML-escaped for security.
  • Selection uses string comparison, so '1' matches 1.
  • Use post('field_name') for single selections and post('field_name[]') for multiple selections.
  • Empty string keys create placeholder options useful for required fields.