PHP中的!is_numeric函数不接受NULL VALUE

xir*_*epe 3 php mysql

我正在尝试验证某个输入,其中用户只能输入整数值...否则将执行错误消息

$user_mcc = $_REQUEST['mobile_countrycode'];
if($user_mcc == ""){
    is_numeric($_REQUEST['mobile_countrycode']);
}

if (!is_numeric($_REQUEST['mobile_countrycode'])){

    echo '<script type="text/javascript">alert("Not a numeric value!\n\nMake sure that your country codes, area codes\nand mobile/fax/phone numbers are correct! \n"); return true;</script>';
    echo '<script type="text/javascript">history.back();</script>'; 
    die('' . mysql_error());



}
Run Code Online (Sandbox Code Playgroud)

我试过这么多的功能,如empty,is_null,== NULL,== 'NULL等...但没有奏效.

如果我将一个字符串值放入输入文本字段,就像我输入的那样... "Banana",!is_numeric可以执行上面的函数,因为输入的值是FALSE而不是数值.

但是,每当我将输入字段留空时NULL,该!is_numeric函数仍然可以执行,就像它将NULL值识别为非数值一样.!is_numeric如果输入值是,我该怎么做才能绕过函数NULL.谢谢.

PS:我已经尝试过!is_int,!is_integer而且ctype_digit,而是回到相同的结果,不接受NULL值.

Ber*_*rak 6

这可能是因为null 它不是数值.它是无效的; 它什么都没有,它肯定不等于整数0.如果你想检查一个数值,或者为null,那么这正是你应该做的:

if( $yourvalue !== null && !is_numeric( $yourvalue ) ) {
}
Run Code Online (Sandbox Code Playgroud)

  • 你应该在调用`is_numeric`之前测试`null` (2认同)
  • @BerryLangerak 那是完全错误的。这根本不是*什么 &amp;&amp; 的意思;如果前半部分为真,它只执行后半部分。参数的顺序通常*极其*重要,绝对不是微优化。 (2认同)