【问题标题】:How to check for numbers only (including negative)?如何仅检查数字(包括负数)?
【发布时间】:2012-03-07 07:56:24
【问题描述】:

我怎样才能只检查从 -10 负数到 +10 正数的数字?

这是我拥有的,但我认为它不安全:

if(isset($_POST['number']) && ctype_digit($_POST['number']) && $_POST['number']>=-10 && $_POST['number']<=10){
    //do something
}

和形式:

Input a number between -10 and 10: <input type="text" name="number" size="5" />

【问题讨论】:

  • 我添加了php标签,以便php社区可以看到你的问题。
  • 当它是一个有限的数字时,为什么要人们输入它?为什么不添加一个选择框?

标签: php numbers negative-number


【解决方案1】:
if( isset($_POST['number'])) {
    $num = intval($_POST['number']);
    if( $num >= -10 && $num <= 10) {
        // do something
    }
}

还有其他方法,但那一种会奏效。任何不能转换为数字的都将被视为零。如果这不是所需的行为,请添加:

&& "".$num == $_POST['number']

到那个内部 IF 语句,以确保没有从输入中删除非数字字符。

【讨论】:

    【解决方案2】:

    检查变量是否为包含零和负值的数字

    $x = '-22';
    if (isNumber($x, ['zero','negative']))
        echo 'Yes';
    else
        echo 'No';
    
    isNumber($x, $includes=[])
    {       
        if (is_int($x)) {
            if ($x === 0) {
                if (in_array('zero', $includes))
                    return true;
            } elseif ($x < 0) {
                if (in_array('negative', $includes))
                    return true;
            } else
                return true;
        } elseif (is_string($x)) {
            if ($x == '0') {
                if (in_array('zero', $includes))
                    return true;
            } elseif ($x[0] == '-') {
                if (in_array('negative', $includes))
                    return ctype_digit(substr($x, 1));
            } else
                return ctype_digit($x);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-04
      • 2015-06-27
      • 2023-03-03
      • 2010-12-19
      • 2020-07-21
      相关资源
      最近更新 更多