is_numeric — 檢測變量是否為數字或數字字符
<?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判定字母等等函數。