检查正整数(PHP)的最佳方法是什么?

我需要检查一个表单输入值是一个正整数(不只是一个整数),我注意到另一个代码片段使用下面的代码:
$i = $user_input_value;
if (!is_numeric($i) || $i < 1 || $i != round($i)) {
  return TRUE;
}
我想知道使用上面的三个检查是否有任何好处,而不仅仅是这样做:
$i = $user_input_value;
if (!is_int($i) && $i < 1) {
  return TRUE;
}
    
已邀请:
你的两个代码片段之间的区别在于,如果$ i是一个数字字符串,
is_numeric($i)
也会返回true,但如果$ i是一个整数,则
is_int($i)
只返回true,而如果$ i是整数字符串则不返回true。这就是为什么你应该使用第一个代码片段,如果你还想要返回true,如果$ i是一个整数字符串(例如,如果$ i ==“19”而不是$ i == 19)。 有关更多信息,请参阅这些参考 php is_numeric函数 php is_int函数     
不知道为什么没有建议在此使用filter_var。我知道这是一个老线程,但也许它会帮助一个人(毕竟,我最终来到这里,对吧?)。
$filter_options = array( 
    'options' => array( 'min_range' => 0) 
);


if( filter_var( $i, FILTER_VALIDATE_INT, $filter_options ) !== FALSE) {
   ...
}
您还可以添加最大值。
$filter_options = array(
    'options' => array( 'min_range' => 0,
                        'max_range' => 100 )
);
http://php.net/manual/en/function.filter-var.php http://www.php.net/manual/en/filter.filters.validate.php     
当变量可以是INTEGER或STRING表示整数时,检查正整数的最佳方法:
 if ((is_int($value) || ctype_digit($value)) && (int)$value > 0 ) { // int }
如果值类型为
integer
,则
is_int()
将返回true。如果类型为
string
,则
ctype_digit()
将返回true,但字符串的值为整数。 此检查与
is_numeric()
之间的区别在于,即使对于表示非整数的数值(例如“+0.123”),
is_numeric()
也将返回true。     
它肯定会走向微优化的领域,但是嘿:我正在研究的代码每天都在咀嚼数百万件物品,而且是周五。所以我做了一些实验......
for ($i = 0; $i < 1000000; $i++) {
    // Option 1: simple casting/equivalence testing
    if ((int) $value == $value && $value > 0) { ... }

    // Option 2: using is_int() and ctype_digit().  Note that ctype_digit implicitly rejects negative values!
    if ((is_int($value) && $value > 0) || ctype_digit($value)) { ... }

    // Option 3: regular expressions
    if (preg_match('/^d+$/', $value)) { ... }
}
然后,我对整数和字符串值运行了上述测试 选项1:简单的铸造/等效测试 整数:0.3秒 字符串:0.4秒 选项2:使用is_int()和ctype_digit() 整数:0.9秒 字符串:1.45秒 选项3:正则表达式 整数:1.83秒 字符串:1.60秒 也许不出所料,选项1是迄今为止最快的,因为没有函数调用,只是转换。值得注意的是,与其他方法不同,选项1将string-float-integer值“5.0”视为整数:
$valList = array(5, '5', '5.0', -5, '-5', 'fred');
foreach ($valList as $value) {
    if ((int) $value == $value && $value > 0) {
        print "Yes: " . var_export($value, true) . " is a positive integern";
    } else {
        print "No: " . var_export($value, true) . " is not a positive integern";
    }
}

Yes: 5 is a positive integer
Yes: '5' is a positive integer
Yes: '5.0' is a positive integer
No: -5 is not a positive integer
No: '-5' is not a positive integer
No: 'fred' is not a positive integer
对于您的特定用例而言,这是否是一件好事还是留给读者的练习......     
检查整数的另一种最佳方法是使用正则表达式。您可以使用以下代码检查Integer值。浮点值将为false。
if(preg_match('/^d+$/',$i)) {
  // valid input.
} else {
  // invalid input.
}
如果你能检查$ i> 0是否更好。     
除了所有其他答案:你可能正在寻找
ctype_digit
。它查找仅包含数字的字符串。     
定义:
!A = !is_numeric($i)
B = $i < 1
!C = $i != round($i)
然后... !is_numeric($ i)|| $ i&lt; 1 || $ i!= round($ i)等于 !A || B || !C 所以:
!A || B || !C = !A || !C || B
现在,使用deMorgan定理,即(!A ||!C)=(A&amp;&amp; C),然后:
!A || !C || B = (A && C) || B
现在,请注意A&amp;&amp; C = is_numeric($ i)&amp;&amp; $ i == round($ i),但如果$ i == round($ i)为TRUE,则is_numeric($ i)也为TRUE,因此我们可以简化A&amp;&amp; C = C所以, (A&amp;&amp; C)|| B = C || B =
$i == round($i) || $i < 1
所以你只需要使用:
$i = $user_input_value;
if ($i == round($i) || $i < 1) {
  return TRUE;
}
    
Laravel 4.2正数的验证规则 它只需要正数,包括浮点值。
public static $rules = array(
    'field_name' => 'required|regex:/^d*.?d*$/'
);
e.g:20,2.6,06     
而不是检查
int
string
与多个条件,如:
if ( ctype_digit($i) || ( is_int($i) && $i > 0 ) )
{
    return TRUE;
}
您可以通过将输入转换为
(string)
来简化此操作,以便一个
ctype_digit
调用将同时检查
string
int
输入:
if( ctype_digit( (string)$i ) )
{
    return TRUE;
}
    
第一个例子是使用
round
来验证输入是一个整数,而不是一个不同的数值(即:十进制)。 如果传递一个字符串,is_int将返回false。有关is_int的信息,请参阅PHP手册示例     
    preg_match('{^[0-9]*$}',$string))
如果你想限制长度:
    preg_match('{^[0-9]{1,3}$}',$string)) //minimum of 1 max of 3
所以pisitive int的最大长度为6:
    if(preg_match('{^[0-9]{1,6}$}',$string)) && $string >= 0)
    
你真的不需要使用所有三个检查,如果你想要一个正整数,你可能想要做与你的代码相反的事情:
if(is_numeric($i) && $i >= 0) { return true; }
有关
is_int()
is_numeric()
之间差异的更多信息,请查看Sören的答案     
要检查正整数使用:
$i = $user_input_value;
if (is_int($i) && $i > 0) {
  return true; //or any other instructions 
}
要么
$i = $user_input_value;
if (!is_int($i) || $i < 1) {
  return false; //or any other instructions 
}
使用符合您目的的那个,因为它们是相同的。以下示例演示了
is_numeric()
is_int()
之间的区别:
is_numeric(0);     // returns true
is_numeric(7);     // returns true
is_numeric(-7);    // returns true
is_numeric(7.2);   // returns true
is_numeric("7");   // returns true
is_numeric("-7");  // returns true
is_numeric("7.2"); // returns true
is_numeric("abc"); // returns false

is_int(0);     // returns true
is_int(7);     // returns true
is_int(-7);    // returns true
is_int(7.2);   // returns false
is_int("7");   // returns false
is_int("-7");  // returns false
is_int("7.2"); // returns false
is_int("abc"); // returns false
    
所有这些答案都忽略了请求者可以检查表单输入的事实。 is_int()将失败,因为表单输入是一个字符串。 对于浮点数,is_numeric()也为true。 这就是为什么$ i == round($ i)进来,因为它检查输入是一个整数。     
好吧,我知道这个帖子真的很老了,但我同意@Jeffrey Vdovjak的意见:既然我能找到它,它可能仍然可以帮助其他人。 php的gmp_sign()可能是另一种简单的方法。它适用于整数和数字字符串,如果a为正则返回1,如果a为负则返回-1,如果a为0则返回0。 所以:
// positive
echo gmp_sign("500") . "n";

// negative
echo gmp_sign("-500") . "n";

// zero
echo gmp_sign("0") . "n";
将输出:
1
-1
0
请参阅http://php.net/manual/en/function.gmp-sign.php上的功能手册 附:您需要在.ini文件中启用php_gmp.dll。     
if(preg_match('/^[1-9]d*$/',$i)) {
   //Positive and > 0
}
    
如果使用“is_int”,则变量必须为整数,因此它不能是浮点值。 (不需要轮次)。     
if(isset($i) && is_int($i) && $i >= 0){ //0 is technically a postive integer I suppose
    return TRUE; //or FALSE I think in your case.
}
    
我会做这样的事情:
if ((int) $i > 0) {
    // this number is positive
}
根据前面的减号,该数字被转换为正数或负数。然后将类型转换数大于0以确定该数字是否为正数。     
这是我的解决方案,希望对您有所帮助:
if (is_numeric($i) && (intval($i) == floatval($i)) && intval($i) > 0)
   echo "positive integer";
我检查字符串是否为数字,第二次检查确定它是整数,第三次确定它是正数     

要回复问题请先登录注册