A PHP string is considered numeric if it can be interpreted as an int or a float.
Formally as of PHP 8.0.0:
WHITESPACES \s* LNUM [0-9]+ DNUM ([0-9]*)[\.]{LNUM}) | ({LNUM}[\.][0-9]*) EXPONENT_DNUM (({LNUM} | {DNUM}) [eE][+-]? {LNUM}) INT_NUM_STRING {WHITESPACES} [+-]? {LNUM} {WHITESPACES} FLOAT_NUM_STRING {WHITESPACES} [+-]? {EXPONENT_DNUM} {WHITESPACES} NUM_STRING ({INT_NUM_STRING} | {FLOAT_NUM_STRING})
PHP also has a concept of leading numeric strings. This is simply a string which starts like a numeric string followed by any characters.
When a string needs to be evaluated as number (e.g. arithmetic operations, int type declaration, etc.) the following steps are taken to determine the outcome:
PHP_INT_MAX
), otherwise resolve to a float. PHP_INT_MAX
), otherwise resolve to a float. Additionally an error of level E_WARNING
is raised. Prior to PHP 8.0.0, a string was considered numeric only if it had leading whitespaces, if it had trailing whitespaces then the string was considered to be leading numeric.
Prior to PHP 8.0.0, when a string was used in a numeric context it would perform the same steps as above with the following differences:
E_NOTICE
instead of an E_WARNING
. E_WARNING
was raised and the value 0
would be returned. <?php $foo = 1 + "10.5"; // $foo is float (11.5) $foo = 1 + "-1.3e3"; // $foo is float (-1299) $foo = 1 + "bob-1.3e3"; // TypeError as of PHP 8.0.0, $foo is integer (1) previously $foo = 1 + "bob3"; // TypeError as of PHP 8.0.0, $foo is integer (1) previously $foo = 1 + "10 Small Pigs"; // $foo is integer (11) and an E_WARNING is raised in PHP 8.0.0, E_NOTICE previously $foo = 4 + "10.2 Little Piggies"; // $foo is float (14.2) and an E_WARNING is raised in PHP 8.0.0, E_NOTICE previously $foo = "10.0 pigs " + 1; // $foo is float (11) and an E_WARNING is raised in PHP 8.0.0, E_NOTICE previously $foo = "10.0 pigs " + 1.0; // $foo is float (11) and an E_WARNING is raised in PHP 8.0.0, E_NOTICE previously ?>
© 1997–2020 The PHP Documentation Group
Licensed under the Creative Commons Attribution License v3.0 or later.
https://www.php.net/manual/en/language.types.numeric-strings.php