Home > Article > Backend Development > PHP determines whether a string is a number
is_numeric — Detect whether a variable is a number or a numeric character (Recommended learning: PHP Programming from Beginner to Master)
<?php $tests = array( "31", 1380, "1e4", "not numeric", array(), 9.1 ); foreach ($tests as $element) { if (is_numeric($element)) { echo "'{$element}' is numeric", PHP_EOL; } else { echo "'{$element}' is NOT numeric", PHP_EOL; } } ?>
Program execution result:
'31' is numeric '1380' is numeric '1e4' is numeric 'not numeric' is NOT numeric 'Array' is NOT numeric '9.1' is numeric
The string 1e4 is also judged as a number.
The is_numeric function not only supports decimal numbers, but also supports hexadecimal type numbers. Therefore, when verifying pure natural numbers such as QQ numbers in use, you must cooperate with the intval() integer function.
<?php $id = 0xff33669f; if (is_numeric($id)) echo $id, '符合要求。';//output 4281558687符合要求。 else echo $id, '不符合要求。'; ?>
If you need to determine an integer, you can use the is_int() function to avoid the situation where some strings are also regarded as legal numbers.
is_numeric can determine whether a variable is a number or a numeric string, but its determination range is too wide. Integers, decimals, exponential representations and hexadecimal values will all pass the judgment. When usually determining the ID, it is a bit inappropriate to use it.
Today I discovered a new judgment function: ctype_digit, which can only judge integers, which is better than is_numeric. Other functions include ctype_xdigit to determine hexadecimal integers, ctype_alpha to determine letters, and so on.
The above is the detailed content of PHP determines whether a string is a number. For more information, please follow other related articles on the PHP Chinese website!