In PHP, intval() converts a value to an integer and returns it. Decimal parts are cut off, not rounded, and text is read from the start.
intval() is the function form of the (int) cast, with one extra feature. When the value is a string, you can pass a base, such as 2, 8 or 16, to read binary, octal or hexadecimal numbers. If a string does not start with a number, the result is 0.
Syntax
Call intval() with the values you need. Start with this line.
PHP
$number = intval($value);
Call
What it does
intval("42")
Returns 42, the string converted to an integer.
intval(42.99)
Returns 42. The decimal part is cut off, not rounded.
intval("ff", 16)
Returns 255, reading the string as a hexadecimal number.
The base only works when the value is a string. For numbers, it is ignored. With a base of 0, PHP checks the prefix of the string: 0x means hex, 0 means octal and 0b means binary, and anything else is decimal.
Library declarations
PHP
intval(mixed $value, int $base = 10): int
Parameters
Parameter
Description
value
Required. The value to convert. Strings are read from the start, up to the first character that cannot belong to a number.
base
Optional. The number base used when the value is a string. The default is 10. Use 0 to detect the base from the prefix, or any value from 2 to 36.
Return Value
Return Value
Description
int
The integer value of the input. Strings that do not start with a number return 0. Empty arrays return 0 and non-empty arrays return 1.
PHP Examples
Example 1 — Converting Strings and Floats
Turn common values into integers and print them with echo.
-3. 9 is truncated toward zero, so the result is -3, not -4.
"1e3" is scientific notation for 1000, and PHP reads it as a number.
null becomes 0, and true becomes 1.
An empty array becomes 0, and any non-empty array becomes 1, no matter what it holds.
Frequently Asked Questions
intval() converts a value to an integer. Decimals are cut off, strings are read from the start, and values that cannot be read as a number become 0.
No. It truncates toward zero, so intval(9.99) is 9 and intval(-9.99) is -9. Use round(), floor() or ceil() first if you need rounding.
Pass the base as the second argument: intval("ff", 16) returns 255 and intval("101", 2) returns 5. With base 0, PHP picks the base from the prefix (0x, 0b or 0).
For most values they are the same. intval() is a function, so you can pass it to array_map(), and it accepts a base for strings. The (int) cast is shorter and has no base option.
It returns 0, with no warning or error. Use is_numeric() or filter_var() with FILTER_VALIDATE_INT first if you need to know whether the input was a real number.