How to Convert a String to a Number in PHP
This snippet is dedicated to one of the common PHP issues: how to convert a string to a number. You can easily do that by following the options we provide.
It is possible to convert strings to numbers in PHP with several straightforward methods.
Below, you can find the three handy methods that we recommend you to use.
Applying Type Casting
The first method is type casting. All you need to do is cast the strings to numeric primitive data types as shown in the example below:
<?php
$num = (int) "10";
$num = (double) "10.12";
// same as (float) "10.12";
?>Note: When converting strings that start with numbers (e.g., "10abc"), PHP extracts the leading numeric value and ignores the trailing characters. Additionally, when converting non-numeric strings (e.g., "abc"), PHP evaluates them as 0.
Performing Math Operations
The second method is to perform math operations on the strings. Here is how you can do it:
<?php
$num = "10" + 1;
$num = floor("10.1");
?>Note: PHP automatically casts strings to numbers during arithmetic operations.
Using intval() or floatval()
The third way of converting a string to a number is using the <kbd class="highlighted">intval()</kbd> or <kbd class="highlighted">floatval()</kbd> functions. These methods are generally applied for converting a string into matching integer and float values.
Here is an example:
<?php
$num = intval("10");
$num = floatval("10.1");
?>