form_search()

function form_search(string $name, ?string $value = null, array $attributes = []): string

Description

Generates an HTML search input field with type="search". Modern browsers provide enhanced search features including a clear button, specialized mobile keyboards, and sometimes integrated history.

Parameters

Parameter Type Description
$name string The name attribute for the search input element.
$value string|null (optional) The initial search query value displayed in the field.
$attributes array (optional) HTML attributes for the search input element. Defaults to an empty array ([]).

Return Value

Type Description
string An HTML search input element with type="search".

Usage Examples

Basic Search Field

PHP
echo form_search('search_query');
// Output: <input type="search" name="search_query">

Search with Placeholder and Constraints

PHP
$attrs = [
    'placeholder' => 'Enter 2-100 characters',
    'minlength' => '2',
    'maxlength' => '100',
    'aria-label' => 'Site search'
];
echo form_search('q', '', $attrs);
// Output: <input type="search" name="q" placeholder="Enter 2-100 characters" minlength="2" maxlength="100" aria-label="Site search">

Pre-populated Search Field

When redisplaying a form after submission, you can retain the user's search term:

PHP
$search_term = post('query', true);
echo form_search('query', $search_term, ['placeholder' => 'Search...']);
// If user searched for "widgets": <input type="search" name="query" value="widgets" placeholder="Search...">
// If no search yet: <input type="search" name="query" placeholder="Search...">

Complete Search Form (GET Method)

Search forms typically use GET method for bookmarkable URLs:

PHP
echo form_open('products/search', ['method' => 'get']);
echo form_search('keywords', post('keywords', true), [
    'placeholder' => 'Product name, SKU, or description',
    'required' => 'required'
]);
echo form_submit('search_btn', 'Find Products');
echo form_close();

Note about browser differences:

  • Most desktop browsers add a clear (×) button when text is entered
  • Mobile devices often show a "search" keyboard with a dedicated search button
  • Safari and Chrome may round the corners of search inputs by default
  • Some browsers maintain a search history for the field
  • **Use GET for searches:** Allows users to bookmark results and share URLs
  • **Provide clear placeholders:** Guide users on what to search for
  • **Set reasonable limits:** Use minlength and maxlength attributes
  • **Consider accessibility:** Add aria-label if label isn't adjacent
  • **Retain search terms:** Use post('field', true) to repopulate after submission
  • **Handle empty searches:** Validate that searches aren't just whitespace