php 检查变量是否为整数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19235746/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 19:04:37  来源:igfitidea点击:

php check to see if variable is integer

phphtmlvalidation

提问by Arian Faurtosh

Is there a nicer way to do this?

有没有更好的方法来做到这一点?

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

I've tried

我试过了

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

But is_int()doesn't work for some reason.

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

My form looks like this

我的表格看起来像这样

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

I've researched is_int(), and it seems that if

我研究过is_int(),似乎如果

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

I've also tried is_numeric()

我也试过 is_numeric()

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

it seems that the only way to do this is:[this is a bad way, do not do it, see note below]

似乎唯一的方法是:[这是一个糟糕的方法,不要这样做,见下面的注释]

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

But is there a function to do the above ?

但是有没有一个功能可以做到以上几点?



Just to clarify, I want the following results

只是为了澄清,我想要以下结果

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


Note: I just figured out my previous solution that I presented will return true for all strings. (thanks redreggae)

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

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

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


This is not a duplicate of Checking if a variable is an integer in PHP, because my requirements/definitions of integer is different than theres.

这不是检查变量是否是 PHP 中的整数的重复,因为我对整数的要求/定义与那里不同。

回答by bitWorking

try ctype_digit

试试ctype_digit

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

Note: It will only work with stringtypes. So you have to cast to stringyour normal variables:

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

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

Also note: It doesn't work with negative integers. If you need this you'll have to go with regex. I found thisfor example:

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

EDIT: Thanks to LajosVeres, I've added the D modifier. So 123\nis not valid.

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

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

More: The simple test with casting will not work since "php" == 0 is trueand "0" === 0 is false! See types comparisons tablefor that.

更多:带有转换的简单测试将不起作用,因为 "php" == 0 istrue并且 "0" === 0 is false!请参阅类型比较表

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

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

回答by IT Vlogs

try filter_varfunction

尝试filter_var功能

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

use:

用:

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

}

回答by Sébastien

In PHP $_POSTvalues are always text (stringtype).

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

You can force a variable into the integer type like this:

您可以将变量强制转换为整数类型,如下所示:

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

That will work if you are certain that $_POST['id']should bean integer. But if you want to make absolutely sure that it contains only numbers from 0to 9and no other signs or symbols use:

如果您确定它$_POST['id']应该是整数,那将起作用。但是,如果您想绝对确保它只包含从0to 开始的数字9而没有其他符号或符号,请使用:

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

回答by siergiej

Check it out: http://php.net/manual/en/function.ctype-digit.php- it validates if string contains only digits, so be sure not to pass an int to that function as it will most likely return false; However all values coming from $_POSTare always strings so you are safe. Also it will not validate negative number such as -18since -is not a digit, but you can always do ctype_digit(ltrim($number, '-'))

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

is_intchecks the variable typewhich in your case is string; it would be the same as (integer)$v === $vas ==does some real obscure things in order to compare two variables of a different type; you should always use ===unless you want mess like "0af5gbd" == 0to return true

is_int检查您的情况下的变量类型string;这将是一样(integer)$v === $v==呢,以比较不同类型的两个变量一些真正晦涩的东西; 你应该总是使用,===除非你想要像"0af5gbd" == 0返回 true一样混乱

Also, keep in mind that ctype_digitwill not tell you if the string can be actually converted to a valid intsince maximum integer value is PHP_INT_MAX; If your value is bigger than that, you will get PHP_INT_MAXanyway.

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

回答by Lajos Veres

preg_match('/^\d+$/D',$variable) //edit 

回答by CaM2091

Using is_numeric()for checking if a variable is an integer is a bad idea. This function will send TRUEfor 3.14for example. It's not the expected behavior

使用is_numeric()检查,如果一个变量是一个整数是一个坏主意。此功能会发送TRUE用于3.14例如。这不是预期的行为

To do this correctly, you can use one of these options :

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

Considering this variables array :

考虑到这个变量数组:

$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
];

The first option (FILTER_VALIDATE_INT Way) :

第一个选项(FILTER_VALIDATE_INT 方式):

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

Output :

输出 :

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 ?

The second option (CASTING COMPARISON Way) :

第二个选项(铸造比较方式):

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

Output :

输出 :

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 ?

The third option (CTYPE_DIGIT Way) :

第三个选项(CTYPE_DIGIT方式):

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

Output :

输出 :

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 ?

The fourth option (REGEX Way) :

第四个选项(REGEX方式):

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

Output :

输出 :

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 ?

回答by glerendegui

if you know it is a string variable (like post o get values), you can use:

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

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

回答by David D

The accepted answer using ctype_digit is correct, however you can make life easier using a function. This will covert the variable to a string, so you don't have to:

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

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

Usage:

用法:

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

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

If you want to accept decimals too, use this:

如果您也想接受小数,请使用以下命令:

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;
}

回答by Andreas

Use the following, universal function to check all types:

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

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

    return false;
}

回答by Luca C.

I use:

我用:

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

Note than this catch only positive integer strings

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