intval() returns the integer value of a scalar and can optionally interpret strings in another base. For validating user input, conversion and validation are different tasks.
$raw = '42';
$number = intval($raw);
echo $number; // 42
$validated = filter_var($raw, FILTER_VALIDATE_INT);
var_dump($validated); // int(42)
This is the recommended starting pattern. The detailed examples below are retained for explanation, comparison and related variations.
intval($value, $base );
$value : the data which integer is returnedecho intval(23); // 23
echo "<br>";
echo intval('23'); // 23
echo "<br>";
echo intval('23.34'); // 23
echo "<br>";
echo intval('023'); // 23
echo "<br>";
echo intval(023); // 19
echo "<br>";
echo intval('23',8); // 19
echo "<br>";
echo intval('2e10'); // 2
echo "<br>";
echo intval(2e10); // -1474836480
This example demonstrates how to convert a string with numeric content into an integer using intval().
$value = "123abc";
$int_value = intval($value);
echo "Converted value: " . $int_value;
Output:
Converted value: 123
This example shows how intval() truncates the decimal part of a float.
$float_value = 45.67;
$int_value = intval($float_value);
echo "Truncated integer: " . $int_value;
Output:
Truncated integer: 45
Use intval() to convert values from different base systems, such as hexadecimal to decimal.
$hex_value = "1A";
$int_value = intval($hex_value, 16);
echo "Hex to integer: " . $int_value;
Output:
Hex to integer: 26
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.