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

ParameterTypeDescription
$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

TypeDescription
stringThe 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:

PHP
echo form_label('Your Name');
echo form_input('user_name');

// Output:
// <label>Your Name</label>
// <input type="text" name="user_name">

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:

PHP
$input_attributes = ['id' => 'email-field'];
$label_attributes = ['for' => 'email-field'];

echo form_label('Email Address', $label_attributes);
echo form_email('user_email', post('user_email'), $input_attributes);

// Output:
// <label for="email-field">Email Address</label>
// <input type="email" name="user_email" id="email-field">

Example #3: Label with CSS Class

PHP
$attributes = [
    'for' => 'newsletter-checkbox',
    'class' => 'form-check-label'
];
echo form_label('Subscribe to Newsletter', $attributes);

// Output:
// <label for="newsletter-checkbox" class="form-check-label">Subscribe to Newsletter</label>

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.