PHP – Convert String to Int

To convert string to int in PHP, you can use Type Casting method or PHP built-in function intval().

In this tutorial, we will go through each of these methods and learn how to convert contents of a string to an integer value.

Convert String to Int using Type Casting

To convert string to integer using Type Casting, provide the literal (int) along with parenthesis before the string literal. The expression returns integer value of the string.

The syntax to type cast string to integer is

$int_value = (int) $string;

In the following example, we will take a string with integer content, and convert the string into integer using type casting.

PHP Program

<?php
$string = "41";
$int_value = (int) $string;
echo $int_value;
?>

Output

PHP - Convert String to Integer using Type Casting

If the string contains a floating value, then the type casting trims out the decimal part.

In the following example, we will take a string which contains a floating value. We shall then typecast the string to integer and observe the output.

PHP Program

<?php
$string = "3.14";
$int_value = (int) $string;
echo $int_value;
?>

Output

PHP - Convert String to Integer using Type Casting

Convert String to Int using intval()

To convert string to integer using PHP built-in function, intval(), provide the string as argument to the function. The function will return the integer value corresponding to the string content.

The syntax to use intval() to convert string to int is

$int_value = intval( $string );

In the following example, we will take a string with integer content, and convert the string into integer using intval() function.

PHP Program

<?php
$string = "41";
$int_value = intval( $string );
echo $int_value;
?>

Output

PHP - Convert String to Int using intval()

As observed in the type casting method, with intval() function value as well, we will get an equivalent integer value if the string contains floating point.

PHP Program

<?php
$string = "3.14";
$int_value = intval( $string );
echo $int_value;
?>

Output

PHP - Convert String to Int using intval()

Conclusion

In this PHP Tutorial, we learned how to convert a string to int using typecasting and intval() function.