PHP: Convert a string into an integer.

In this tutorial, we will show you how to convert a string into an integer using PHP.

There are two ways of doing this.

You can either cast the string as an int, or you can use the function intval.

Casting a string to an int.

To cast a string to an integer value, you can use what is known as “type casting”:

//Our string, which contains the
//number 2.
$num = "2";

//Cast it to an integer value.
$num = (int) $num;

//var_dump it out to the page

If you run the code snippet above, you will see that the output is: int 2

Using the intval function.

You can also use the built-in PHP function intval, which returns a variable’s integer value:

//Our string variable.
$num = "2";

//Use the intval function to convert it
$num = intval($num);

//var_dump it out to the page

The snippet above will print out the exact same result as the code in the first “type casting” example.

Where are my decimal places gone?

An integer is a whole number. It is not a fraction. Therefore, any decimal places will be lost during the conversion.

That means that 2.22 will become 2 and 7.67 will become 7.

Note that intval will not round the decimals to the closest integer. Instead, it will always round it down. For example, 9.99 will become 9, not 10.

If you need to convert your string into a number that retains its decimal places, then you can check out our guide on parsing a string as a float value.

Do I really need to convert my PHP strings into integers?

In most cases, you will not need to convert your strings into integer values.

This is because, unlike other programming languages, PHP is weakly typed and will automatically “figure it out” for you.

For example, if you are doing simple math, then PHP will automatically convert the variable for you.

Take the following example, where we get the sum of two string variables that contain numbers:

//Number A
$numA = "9";

//Number B
$numB = "2";

//Get the sum of our two numbers.
$sum = $numA + $numB;

//Print out the result

If you run the code above, you will see that the output is: int 11.

This is because PHP looked at our two variables and presumed that we were trying to get the sum of two integer values.

Note that you can technically use this “feature” to convert a string into an int:

$numA = "2";

$numA = $numA + 0;

var_dump($numA); //becomes int 2

Although this code will work, we recommend that you use one of the other two methods instead.

The problem with this approach is that the intent of your code will be far less clear to others.

In other words, it may confuse other developers.