form_number()
function form_number(string $name, string|int|float|null $value = null, array $attributes = []): string
Description
Generates an HTML number input field with type="number". Provides built-in browser number validation and step controls.
Parameters
| Parameter | Type | Description |
|---|---|---|
| $name | string | The name attribute for the input element. |
| $value | string|int|float|null | (optional) The numeric value for the input. |
| $attributes | array | (optional) HTML attributes for the input element. Defaults to an empty array ([]). |
Return Value
| Type | Description |
|---|---|
| string | An HTML number input element. |
Example #1: Basic Number Input
PHP
echo form_number('quantity', 5);
// Output:
// <input type="number" name="quantity" value="5">Example #2: Number Input with Range and Step
PHP
$attributes = [
'min' => '0',
'max' => '100',
'step' => '5'
];
echo form_number('percentage', 50, $attributes);
// Output:
// <input type="number" name="percentage" value="50" min="0" max="100" step="5">Example #3: Decimal Number Input
PHP
$attributes = [
'min' => '0.00',
'max' => '1000.00',
'step' => '0.01',
'placeholder' => '0.00'
];
echo form_number('price', '', $attributes);
// Output:
// <input type="number" name="price" min="0.00" max="1000.00" step="0.01" placeholder="0.00">Number Input Attributes Explained
Number inputs support specialized attributes that control validation and user interaction:
min and max
The min and max attributes define the allowable numeric range. Browsers prevent values outside this range:
HTML
<input type="number" min="1" max="10"> <!-- Only 1 through 10 allowed -->step
The step attribute controls the increment/decrement values when using arrow keys or spinner buttons:
HTML
<input type="number" step="1"> <!-- Whole numbers only: 1, 2, 3 -->
<input type="number" step="0.5"> <!-- 0.5 increments: 1, 1.5, 2 -->
<input type="number" step="0.01"> <!-- Two decimal places -->
<input type="number" step="any"> <!-- Any decimal value allowed -->The default step value is 1, which restricts input to whole numbers.
- Use
minandmaxattributes to restrict number ranges for better user experience. - For currency values, use
step="0.01"to enforce two decimal places. - Use
post('field_name', true, true)to automatically cast submitted values to integers or floats. - Always validate numbers server-side with PHP's
filter_var($value, FILTER_VALIDATE_FLOAT)oris_numeric(). - Remember that browser validation varies - some users may submit values outside allowed ranges.
- Number inputs trigger numeric keyboards on mobile devices, improving data entry.