PHP: Convert a string into an integer.

This is a beginner’s tutorial on how to convert a string into an integer using PHP. In this guide, I will show you two different ways to accomplish this.

Casting a string to an int.

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

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 inbuilt PHP function intval, which will return the integer value of a variable:

The PHP above will output the exact same result as the code in the first “type casting” example.

Wait? Where are my decimal places gone?

An integer is a whole number. A whole number is not a fraction and therefore, any decimal places will be “lost” during the conversion. i.e. 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 my guide on parsing a string as a float value.

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

In the vast majority of cases, you will not need to convert your PHP strings into integer values. This is because unlike other programming languages, PHP is weakly typed and will automatically “figure it out” for you.

If you are using any of the arithmetic operators, 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:

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:

Although this approach will work, I would not recommend using it over the other two methods that were outlined above. The problem with this approach is that the intent of your code will be far less clear to others. As a result, it may confuse other developers.

Facebook Comments