Backend Development 4 min read

Using PHP intval() to Convert Variables to Integers

This article explains how PHP's built‑in intval() function converts different variable types—including strings, floating‑point numbers, and values in other bases—into integers, illustrating usage with code examples and noting that failed conversions return zero.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP intval() to Convert Variables to Integers

In PHP, variable types are dynamic, but you can explicitly convert a value to an integer using the built‑in intval() function.

The syntax is intval($value, $base) , where $value is the variable to convert and $base (optional) specifies the numeral system, defaulting to base 10.

Example 1: Converting strings to integers

$num1 = "10";
$num2 = "20.5";
$num3 = "abc";

$int1 = intval($num1);
$int2 = intval($num2);
$int3 = intval($num3);

echo $int1; // 10
echo $int2; // 20
echo $int3; // 0

This shows that numeric strings are converted to their integer values, while non‑numeric strings result in 0.

Example 2: Converting floating‑point numbers to integers

$num1 = 10.5;
$num2 = 20.8;

$int1 = intval($num1);
$int2 = intval($num2);

echo $int1; // 10
echo $int2; // 20

Floating‑point numbers are truncated, keeping only the integer part.

Example 3: Specifying the conversion base

$hex = "0x1A";   // hexadecimal, equals 26 decimal
$binary = "1100"; // binary, equals 12 decimal

$int1 = intval($hex, 16);
$int2 = intval($binary, 2);

echo $int1; // 26
echo $int2; // 12

By providing the second argument, intval() interprets the string in the given base and returns the corresponding decimal integer.

In summary, intval() converts various variable types to integers, returns 0 when conversion fails, and can handle different numeral bases when the optional base parameter is supplied.

PHPType ConversionIntegerbase conversionintval
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.