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
| Parameter | Type | Description |
|---|---|---|
| $name | string | The name attribute for the select element. |
| $options | array<string|int,string> | Associative array where keys are option values and values are display text. |
| $selected_key | string|int|null | (optional) The key of the option that should be selected. |
| $attributes | array | (optional) HTML attributes for the select element. Defaults to an empty array ([]). |
Return Value
| Type | Description |
|---|---|
| string | The generated HTML select menu with options. |
Example #1: Basic Dropdown
PHP
$options = [
'small' => 'Small',
'medium' => 'Medium',
'large' => 'Large'
];
echo form_dropdown('size', $options);Example #2: Dropdown with Selected Value
PHP
$options = [
'pending' => 'Pending',
'in_progress' => 'In Progress',
'completed' => 'Completed'
];
echo form_dropdown('status', $options, 'in_progress');Example #3: Dropdown with Placeholder Option
PHP
$options = [
'' => '-- Select Country --',
'us' => 'United States',
'ca' => 'Canada'
];
$attributes = ['required' => 'required'];
echo form_dropdown('country', $options, '', $attributes);Example #4: Multiple Selection Dropdown
PHP
$options = [
'php' => 'PHP',
'js' => 'JavaScript',
'python' => 'Python'
];
$attributes = [
'multiple' => 'multiple',
'size' => '3'
];
echo form_dropdown('languages[]', $options, ['php', 'python'], $attributes);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'matches1. - Use
post('field_name')for single selections andpost('field_name[]')for multiple selections. - Empty string keys create placeholder options useful for required fields.