is_numeric — 检测变量是不是为数字或数字字符(引荐进修:PHP编程从入门到通晓)
<?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; } } ?>
顺序运转效果:
'31' is numeric '1380' is numeric '1e4' is numeric 'not numeric' is NOT numeric 'Array' is NOT numeric '9.1' is numeric
字符串 1e4 也被剖断为数字了。
is_numeric函数不只支撑10进制的数字,也支撑16进制范例数字。所以在运用中考证纯天然数字如QQ号码如许的数字串,要合营 intval()整型化函数。
<?php $id = 0xff33669f; if (is_numeric($id)) echo $id, '符合请求。';//output 4281558687符合请求。 else echo $id, '不符合请求。'; ?>
假如须要推断整数,能够运用 is_int()函数,以避免发作一些字符串也当做是正当数字的状况。
is_numeric能剖断一个变量是不是为数字或数字字符串,然则它的剖断局限太宽了。整数、小数、指数示意以及16进制数值都邑经由过程推断。 日常平凡剖断id的时刻,用它就有点不合适。
本日发明一个新的剖断函数:ctype_digit,它能够只剖断整数,如许就比is_numeric好一些。其他另有ctype_xdigit剖断16进制整数,ctype_alpha剖断字母等等函数。
以上就是php推断字符串是不是为数字的细致内容,更多请关注ki4网别的相干文章!