【问题标题】:php check to see if variable is integerphp 检查变量是否为整数
【发布时间】:2013-10-14 16:05:12
【问题描述】:

有更好的方法吗?

if( $_POST['id'] != (integer)$_POST['id'] )
    echo 'not a integer';

我试过了

if( !is_int($_POST['id']) )

is_int() 出于某种原因不起作用。

我的表单是这样的

<form method="post">
   <input type="text" name="id">
</form>

我研究过is_int(),好像如果

is_int('23'); // would return false (not what I want)
is_int(23);   // would return true

我也试过is_numeric()

is_numeric('23'); // return true
is_numeric(23); // return true
is_numeric('23.3'); // also returns true (not what I want)

看来唯一的办法是: [这是不好的办法,不要这样做,见下面的注释]

if( '23' == (integer)'23' ) // return true
if( 23 == (integer)23 ) // return true
if( 23.3 == (integer)23.3 ) // return false
if( '23.3' == (integer)'23.3') // return false

但是有没有实现上述功能的功能?


澄清一下,我想要以下结果

23     // return true
'23'   // return true
22.3   // return false
'23.3' // return false

注意:我刚刚发现我之前提出的解决方案将对所有字符串返回 true。 (感谢 redreggae)

$var = 'hello';
if( $var != (integer)$var )
    echo 'not a integer';

// will return true! So this doesn't work either.

这不是Checking if a variable is an integer in PHP 的重复,因为我对整数的要求/定义与那里不同。

【问题讨论】:

  • 试试 RegEXP。 preg_match('/^[\d]*$/',$variable)!==FALSE
  • 为什么需要“验证”?你不能只过滤值吗?所以: $input = (int)$_POST['id'] 。这将为您提供 100% 安全的整数(如果出现问题,则为 0),并且更容易处理......
  • @Qualcuno 我正在考虑这个问题,但我想通知用户他们没有输入正确的数字并且不要为他们更改。
  • var_dump($_POST["id"]) 怎么样,这会告诉你数据类型;
  • 为什么?假设他/她键入“aaa”,它将变为 0,您将拒绝它,就像您拒绝输入 0 一样。(因为它是一个 id,所以我想它会 > 0)。您只会告诉您的用户“输入错误”,无需进一步详细说明!

标签: php html validation


【解决方案1】:

试试ctype_digit

if (!ctype_digit($_POST['id'])) {
    // contains non numeric characters
}

注意:它只适用于string 类型。所以你必须将你的正常变量转换为string

$var = 42;
$is_digit = ctype_digit((string)$var);

另请注意:它不适用于负整数。如果你需要这个,你将不得不使用正则表达式。例如,我找到了this

编辑:感谢 LajosVeres,我添加了 D 修饰符。所以123\n 无效。

if (preg_match("/^-?[1-9][0-9]*$/D", $_POST['id'])) {
    echo 'String is a positive or negative integer.';
}

更多:使用强制转换的简单测试将不起作用,因为 "php" == 0 是 true 而 "0" === 0 是 false! 请参阅types comparisons table

$var = 'php';
var_dump($var != (int)$var); // false

$var = '0';
var_dump($var !== (int)$var); // true

【讨论】:

  • $integer = 42; ctype_digit($integer); 将返回 false
  • 是的..如果您使用“正常”变量而不是 $_GET 或 $_POST 来检查它,而不是首先转换为 string$is_digit = ctype_digit((string)42);
  • @aaron 这是正确的,需要输入一个字符串。幸运的是,对于 $_POST 值,它们始终是字符串。
  • @GeoffreyHuck 好吧,一旦你用过它们,它们就不会不为人知了......我认为ctype_digit 应该比is_numeric 更频繁地使用,后者的名字更令人难忘,但实际上很少是您想要执行的测试。
  • 您需要对 preg_match 使用 D 修饰符。而且它不接受 0 到数字。
【解决方案2】:

试试filter_var函数

filter_var($_POST['id'], FILTER_VALIDATE_INT);

使用:

if(filter_var($_POST['id'], FILTER_VALIDATE_INT)) { 
    //Doing somethings...

}

【讨论】:

    【解决方案3】:

    在 PHP 中,$_POST 值始终是文本(string 类型)。

    您可以像这样将变量强制转换为整数类型:

    $int_id = (int)$_POST['id'];
    

    如果您确定$_POST['id'] 应该是一个整数,这将起作用。但是,如果您想绝对确保它仅包含从 09 的数字,并且没有使用其他符号或符号:

    if( ctype_digit( $_POST['id'] ) )
    {
      $int_id = (int)$_POST['id'];
    }
    

    【讨论】:

    • 不正确:$_POST 可以是数组。
    【解决方案4】:

    使用is_numeric() 检查变量是否为整数是个坏主意。 例如,此函数将为 3.14 发送 TRUE。这不是预期的行为

    要正确执行此操作,您可以使用以下选项之一:

    考虑这个变量数组:

    $variables = [
        "TEST 0" => 0,
        "TEST 1" => 42,
        "TEST 2" => 4.2,
        "TEST 3" => .42,
        "TEST 4" => 42.,
        "TEST 5" => "42",
        "TEST 6" => "a42",
        "TEST 7" => "42a",
        "TEST 8" => 0x24,
        "TEST 9" => 1337e0
    ];
    

    第一个选项(FILTER_VALIDATE_INT方式):

    # Check if your variable is an integer
    if( ! filter_var($variable, FILTER_VALIDATE_INT) ){
      echo "Your variable is not an integer";
    }
    

    输出:

    TEST 0 : 0 (type:integer) is not an integer ✘
    TEST 1 : 42 (type:integer) is an integer ✔
    TEST 2 : 4.2 (type:double) is not an integer ✘
    TEST 3 : 0.42 (type:double) is not an integer ✘
    TEST 4 : 42 (type:double) is an integer ✔
    TEST 5 : 42 (type:string) is an integer ✔
    TEST 6 : a42 (type:string) is not an integer ✘
    TEST 7 : 42a (type:string) is not an integer ✘
    TEST 8 : 36 (type:integer) is an integer ✔
    TEST 9 : 1337 (type:double) is an integer ✔
    

    第二种选择(CASTING COMPARISON方式):

    # Check if your variable is an integer
    if ( strval($variable) != strval(intval($variable)) ) {
      echo "Your variable is not an integer";
    }
    

    输出:

    TEST 0 : 0 (type:integer) is an integer ✔
    TEST 1 : 42 (type:integer) is an integer ✔
    TEST 2 : 4.2 (type:double) is not an integer ✘
    TEST 3 : 0.42 (type:double) is not an integer ✘
    TEST 4 : 42 (type:double) is an integer ✔
    TEST 5 : 42 (type:string) is an integer ✔
    TEST 6 : a42 (type:string) is not an integer ✘
    TEST 7 : 42a (type:string) is not an integer ✘
    TEST 8 : 36 (type:integer) is an integer ✔
    TEST 9 : 1337 (type:double) is an integer ✔
    

    第三个选项(CTYPE_DIGIT方式):

    # Check if your variable is an integer
    if( ! ctype_digit(strval($variable)) ){
      echo "Your variable is not an integer";
    }
    

    输出:

    TEST 0 : 0 (type:integer) is an integer ✔
    TEST 1 : 42 (type:integer) is an integer ✔
    TEST 2 : 4.2 (type:double) is not an integer ✘
    TEST 3 : 0.42 (type:double) is not an integer ✘
    TEST 4 : 42 (type:double) is an integer ✔
    TEST 5 : 42 (type:string) is an integer ✔
    TEST 6 : a42 (type:string) is not an integer ✘
    TEST 7 : 42a (type:string) is not an integer ✘
    TEST 8 : 36 (type:integer) is an integer ✔
    TEST 9 : 1337 (type:double) is an integer ✔
    

    第四个选项(REGEX方式):

    # Check if your variable is an integer
    if( ! preg_match('/^\d+$/', $variable) ){
      echo "Your variable is not an integer";
    }
    

    输出:

    TEST 0 : 0 (type:integer) is an integer ✔
    TEST 1 : 42 (type:integer) is an integer ✔
    TEST 2 : 4.2 (type:double) is not an integer ✘
    TEST 3 : 0.42 (type:double) is not an integer ✘
    TEST 4 : 42 (type:double) is an integer ✔
    TEST 5 : 42 (type:string) is an integer ✔
    TEST 6 : a42 (type:string) is not an integer ✘
    TEST 7 : 42a (type:string) is not an integer ✘
    TEST 8 : 36 (type:integer) is an integer ✔
    TEST 9 : 1337 (type:double) is an integer ✔
    

    【讨论】:

      【解决方案5】:

      检查一下:http://php.net/manual/en/function.ctype-digit.php - 它验证字符串是否仅包含数字,因此请确保不要将 int 传递给该函数,因为它很可能会返回 false;但是,来自$_POST 的所有值始终是字符串,因此您是安全的。此外,它不会验证负数,例如 -18,因为 - 不是数字,但您始终可以使用 ctype_digit(ltrim($number, '-'))

      is_int 检查变量 type 在您的情况下是 string;它与(integer)$v === $v 相同,因为== 做了一些真正晦涩难懂的事情来比较两个不同类型的变量;您应该始终使用===,除非您希望像"0af5gbd" == 0 这样的混乱返回true

      另外,请记住ctype_digit 不会告诉您字符串是否可以实际转换为有效的int,因为最大整数值为PHP_INT_MAX;如果你的值大于这个值,无论如何你都会得到PHP_INT_MAX

      【讨论】:

      • ltrim($number, '-') 的好主意..但请记住 ---123 将以这种方式工作。
      【解决方案6】:
      preg_match('/^\d+$/D',$variable) //edit 
      

      【讨论】:

        【解决方案7】:

        如果你知道它是一个字符串变量(比如 post o get values),你可以使用:

        function is_really_integer($var) {
          return $var == (string)(integer)$var;
        }
        

        【讨论】:

        • 这是我做的,而且速度非常快
        【解决方案8】:

        使用 ctype_digit 的公认答案是正确的,但是您可以使用函数让生活更轻松。这会将变量转换为字符串,因此您不必:

        function is_num($x){
            if(!is_string($x)){
                $x=(string)$x;
            }
            if(ctype_digit($x)){
              return true;
            }
            return false;
        }
        

        用法:

        if (is_num(56)) {
            // its a number
        }
        
        if (is_num('56')) {
            // its a number
        }
        

        如果你也想接受小数,使用这个:

        function is_num($x){
            if(!is_string($x)){
                $x=(string)$x;
            }    
            if (strpos($x,'.')!==false) {      
                if(substr_count($x,'.')>1||strpos($x,'.')<1||strpos($x,'.')>=strlen($x)){
                    return false;    
                }
                $x=str_replace('.','',$x);    
            }
            if(ctype_digit($x)){
                return true;
            }  
            return false;
        }
        

        【讨论】:

          【解决方案9】:

          使用 filter_var 但要小心它返回 bool。

          如果你有字符串 '0' => 你会得到 false

          正确使用方法:

          if (filter_var($_POST['id'], FILTER_VALIDATE_INT) !== false) { 
              // Doing somethings...
          }
          

          【讨论】:

            【解决方案10】:

            使用以下通用函数检查所有类型:

            function is_digit($mixed) {
                if(is_int($mixed)) {
                    return true;
                } elseif(is_string($mixed)) {
                    return ctype_digit($mixed);
                }
            
                return false;
            }
            

            【讨论】:

              【解决方案11】:

              我用:

              is_int($val)||ctype_digit($val)
              

              请注意,这仅捕获正整数字符串

              【讨论】:

                【解决方案12】:

                is_int 完美运行,无需额外代码

                或者您可以使用is_numeric进行检查

                【讨论】:

                • 如果您阅读了我的问题,您就会明白为什么 is_intis_numeric 没有给我正确的值。
                猜你喜欢
                • 2011-01-12
                • 2011-09-18
                • 2014-01-25
                • 1970-01-01
                • 2015-02-25
                • 2011-03-30
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多