form_label()
function form_label(string $label_text, array $attributes = []): string
Description
Generates an HTML <label> element. Labels improve accessibility and usability by associating descriptive text with form input fields.
Parameters
| Parameter | Type | Description |
|---|---|---|
| $label_text | string | The text or HTML content displayed inside the label. **Note:** This is not automatically escaped. |
| $attributes | array | (optional) HTML attributes for the label element, such as for, class, or id. Defaults to an empty array ([]). |
Return Value
| Type | Description |
|---|---|
| string | The generated HTML label element. |
Example #1: Basic Label (Implicit Association)
When placed directly before the input field, the association is often implied by the browser:
Example #2: Explicit Association (Best Practice)
Using the for attribute to link the label to an input's id is the best practice for accessibility:
Example #3: Label with CSS Class
Security Warning: The $label_text is not automatically HTML-escaped. If this value comes from user input (e.g., a database record name), you must manually sanitize it (e.g., using htmlentities() or out()) before passing it to `form_label()` to prevent XSS vulnerabilities.
Always associate labels with inputs using the for attribute pointing to the input's id attribute.