How do I convert a string to a number in PHP?
I want to convert these types of values, '3'
, '2.34'
, '0.234343'
, etc. to a number. In JavaScript we can use Number()
, but is there any similar method available in PHP?
Input Output
'2' 2
'2.34' 2.34
'0.3454545' 0.3454545
Solution 1:
You don't typically need to do this, since PHP will coerce the type for you in most circumstances. For situations where you do want to explicitly convert the type, cast it:
$num = "3.14";
$int = (int)$num;
$float = (float)$num;
Solution 2:
There are a few ways to do so:
-
Cast the strings to numeric primitive data types:
$num = (int) "10"; $num = (double) "10.12"; // same as (float) "10.12";
-
Perform math operations on the strings:
$num = "10" + 1; $num = floor("10.1");
-
Use
intval()
orfloatval()
:$num = intval("10"); $num = floatval("10.1");
Use
settype()
.
Solution 3:
To avoid problems try intval($var)
. Some examples:
<?php
echo intval(42); // 42
echo intval(4.2); // 4
echo intval('42'); // 42
echo intval('+42'); // 42
echo intval('-42'); // -42
echo intval(042); // 34 (octal as starts with zero)
echo intval('042'); // 42
echo intval(1e10); // 1410065408
echo intval('1e10'); // 1
echo intval(0x1A); // 26 (hex as starts with 0x)
echo intval(42000000); // 42000000
echo intval(420000000000000000000); // 0
echo intval('420000000000000000000'); // 2147483647
echo intval(42, 8); // 42
echo intval('42', 8); // 34
echo intval(array()); // 0
echo intval(array('foo', 'bar')); // 1
?>
Solution 4:
In whatever (loosely-typed) language you can always cast a string to a number by adding a zero to it.
However, there is very little sense in this as PHP will do it automatically at the time of using this variable, and it will be cast to a string anyway at the time of output.
Note that you may wish to keep dotted numbers as strings, because after casting to float it may be changed unpredictably, due to float numbers' nature.
Solution 5:
If you want get a float for $value = '0.4'
, but int for $value = '4'
, you can write:
$number = ($value == (int) $value) ? (int) $value : (float) $value;
It is little bit dirty, but it works.