is_numeric — 检测变量是否为数字或数字字符串。
基本使用如下:
<?php $tests = array( "42", 1337, "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; } } ?>
程序运行结果:
'42' is numeric '1337' 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函数补完:get_magic_quotes_gpc()
- PHP函数补完:error_reporting()
- PHP函数补完:preg_match()
- PHP函数补完:urlencode()
- PHP函数补完:array_multisort()
- PHP函数补完:array_splice()
- PHP函数补完:isset()
- PHP函数补完:getenv()
- PHP函数补完:header()
- PHP函数补完:mysql_num_rows()
- PHP函数补完:list()
- PHP函数补完:mysql_query()
- PHP函数补完:mysql_fetch_array()
- PHP函数补完:number_format()
- PHP函数补完:explode()
- PHP函数补完:call_user_func()
- PHP函数补完:ImageCopyResamples()
- PHP函数补完:import_request_variables()
- PHP函数补完:parse_url()
- PHP函数补完:移除HTML标签strip_tags()
- PHP函数补完:输出数组结构与内容var_dump()
- PHP函数补完:var_export()
- PHP函数补完:判断变量是否为数字is_numeric()
- PHP函数补完:session_name()
- PHP函数补完:session_id()
- PHP函数补完:nl2br()与nl2p()函数
- PHP函数补完:shuffle()取数组若干个随机元素
- PHP函数补完:http_build_query()构造URL字符串
- PHP函数补完:stream_context_create()模拟POST/GET
本文地址:http://www.nowamagic.net/librarys/veda/detail/2023,欢迎访问原出处。
大家都在看