intval
Converts a value to an integer.
Syntax
intval(mixed $value, int $base = 10): intParameters
| Parameter | Type | Description |
|---|---|---|
| $value | mixed | A string, a number or a boolean. |
| $base | int | Optional. The base for strings. |
Return value
intAn integer; `0` if the conversion failed.
Examples
A string, a fraction and text:
<?php
echo intval('42'), "\n";
echo intval(7.9), "\n";
echo intval('12 apples'), "\n";
echo intval('apples');Output:
42
7
12
0The (int) cast does the same:
<?php
echo (int) '42' + 1;Output:
43Notes
The fraction is dropped, not rounded. A non-numeric string silently becomes 0 — if that is an error, check the value with is_numeric() first.
See also
- is_numeric — Checks whether a value is a number or a numeric string.
- round — Rounds a number to a given number of digits.
- floor — Rounds a number down to the nearest integer.
Related recipes
In the tutorial
- Data types — The main PHP data types — strings, numbers, booleans, arrays and null.