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
For situations when you do know the target type (as you should), one of the type casting operators can be used:
$num = "42";
$int = (int)$num;
$num = "3.14";
$float = (float)$num;
as well as one of their aliases, such as intval()
, floatval()
or settype()
.
Notice that PHP would try to make a number from such not-so-numeric strings as " 42 "
, or "42 The Answer to the Ultimate Question of Life, the Universe, and Everything"
- by applying trim() and picking the leading number before conversion. Scientific notation is also recognized.
When you don't know the target type, a simple arithmetic operation, $num + 0
, or $num * 1
can be used, as well as identity operator suggested in this answer (which seems to be an alias for the latter calculation):
$num = "42";
$int = +$num;
$num = "3.14";
$float = +$num;
However, unlike casting operators, these calculations would raise a Type error, when source value is not numeric (and a Warning then it's not-so-numeric). Which is a good thing, because you cannot get a sensible result from making a number from string 'foo' or an array. Consider validating/normalizing input values to avoid such errors.