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”:
//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 var_dump($num);
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:
//Our string variable. $num = "2"; //Use the intval function to convert it $num = intval($num); //var_dump it out to the page var_dump($num);
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:
//Number A $numA = "9"; //Number B $numB = "2"; //Get the sum of our two numbers. $sum = $numA + $numB; //Print out the result var_dump($sum);
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 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.