检查正整数(PHP)的最佳方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4844916/
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
Best way to check for positive integer (PHP)?
提问by geerlingguy
I need to check for a form input value to be a positive integer (not just an integer), and I noticed another snippet using the code below:
我需要检查表单输入值是否为正整数(不仅仅是整数),并且我注意到另一个使用以下代码的代码段:
$i = $user_input_value;
if (!is_numeric($i) || $i < 1 || $i != round($i)) {
return TRUE;
}
I was wondering if there's any advantage to using the three checks above, instead of just doing something like so:
我想知道使用上述三个检查是否有任何优势,而不仅仅是这样做:
$i = $user_input_value;
if (!is_int($i) && $i < 1) {
return TRUE;
}
采纳答案by S?ren
the difference between your two code snippets is that is_numeric($i)
also returns true if $i is a numeric string, but is_int($i)
only returns true if $i is an integer and not if $i is an integer string. That is why you should use the first code snippet if you also want to return true if $i is an integer string(e.g. if $i == "19" and not $i == 19).
您的两个代码片段之间的区别在于,is_numeric($i)
如果 $i 是数字字符串也返回 true ,但is_int($i)
仅当 $i 是整数而不是 $i 是整数字符串时才返回 true 。这就是为什么如果您还想在 $i 是整数字符串时返回 true (例如,如果 $i == "19" 而不是 $i == 19),您应该使用第一个代码片段。
See these references for more information:
有关更多信息,请参阅这些参考资料:
回答by Jeff Vdovjak
Not sure why there's no suggestion to use filter_var
on this. I know it's an old thread, but maybe it will help someone out (after all, I ended up here, right?).
不知道为什么没有建议使用filter_var
这个。我知道这是一个旧线程,但也许它会帮助某人(毕竟,我最终到了这里,对吧?)。
$filter_options = array(
'options' => array( 'min_range' => 0)
);
if( filter_var( $i, FILTER_VALIDATE_INT, $filter_options ) !== FALSE) {
...
}
You could also add a maximum value as well.
您还可以添加最大值。
$filter_options = array(
'options' => array( 'min_range' => 0,
'max_range' => 100 )
);
Learn more about filters.
了解有关过滤器的更多信息。
回答by Christian P
The best way for checking for positive integers when the variable can be INTEGER or STRING representing the integer:
当变量可以是表示整数的 INTEGER 或 STRING 时,检查正整数的最佳方法:
if ((is_int($value) || ctype_digit($value)) && (int)$value > 0 ) { // int }
is_int()
will return true if the value type is integer
. ctype_digit()
will return true if the type is string
but the value of the string is an integer.
is_int()
如果值类型为 ,则返回 true integer
。ctype_digit()
如果类型是string
但字符串的值是整数,则返回 true 。
The difference between this check and is_numeric()
is that is_numeric()
will return true even for the values that represent numbers that are not integers (e.g. "+0.123").
此检查与此检查之间的区别在于is_numeric()
,is_numeric()
即使对于表示不是整数的数字(例如“+0.123”)的值也将返回 true。
回答by Jamie Mann
It's definitely heading towards the land of micro-optimisation, but hey: the code I'm working on chews through millions of items every day and it's Friday. So I did a little bit of experimenting...
它肯定会朝着微优化的方向发展,但是嘿:我正在处理的代码每天都在咀嚼数百万个项目,现在是星期五。所以我做了一些实验......
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)) { ... }
}
I then ran the above tests for both integer and string values
然后我对整数和字符串值进行了上述测试
Option 1: simple casting/equivalence testing
选项 1:简单的铸造/等效测试
- Integer: 0.3s
- String: 0.4s
- 整数:0.3s
- 字符串:0.4s
Option 2: using is_int() and ctype_digit()
选项 2:使用 is_int() 和 ctype_digit()
- Integer: 0.9s
- String: 1.45s
- 整数:0.9s
- 字符串:1.45s
Option 3: regular expressions
选项 3:正则表达式
- Integer: 1.83s
- String: 1.60s
- 整数:1.83s
- 字符串:1.60s
Perhaps unsurprisingly, option 1 is by far the quickest, since there's no function calls, just casting. It's also worth noting that unlike the other methods, option 1 treats the string-float-integer value "5.0" as an integer:
也许不出所料,选项 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 integer\n";
} else {
print "No: " . var_export($value, true) . " is not a positive integer\n";
}
}
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
Whether or not that's a good thing for your particular use-case is left as an exercise for the reader...
这对于您的特定用例是否是一件好事,留给读者作为练习......
回答by Harsha
The other best way to check a Integer number is using regular expression. You can use the following code to check Integer value. It will false for float values.
检查整数的另一种最佳方法是使用正则表达式。您可以使用以下代码来检查整数值。对于浮点值,它将为 false。
if(preg_match('/^\d+$/',$i)) {
// valid input.
} else {
// invalid input.
}
It's better if you can check whether $i > 0 too.
如果您也可以检查 $i > 0 是否更好。
回答by Miguel A. Carrasco
Definition:
定义:
!A = !is_numeric($i)
B = $i < 1
!C = $i != round($i)
Then...
然后...
!is_numeric($i) || $i < 1 || $i != round($i) is equal to !A || B || !C
!is_numeric($i) || $i < 1 || $i != round($i)等于!A || 乙|| !C
So:
所以:
!A || B || !C = !A || !C || B
Now, using the deMorgan theorem, i.e. (!A || !C) = (A && C), then:
现在,使用德摩根定理,即 (!A || !C) = (A && C),则:
!A || !C || B = (A && C) || B
Now, note that A && C = is_numeric($i) && $i == round($i), but if $i == round($i) is TRUE, then is_numeric($i) is TRUE as well, so we can simplify A && C = C so,
现在,请注意 A && C = is_numeric($i) && $i == round($i),但是如果 $i == round($i) 为 TRUE,那么 is_numeric($i) 也为 TRUE,所以我们可以简化 A && C = C 所以,
(A && C) || B = C || B =
(A && C) || B = C|| 乙 =
$i == round($i) || $i < 1
So you just need to use:
所以你只需要使用:
$i = $user_input_value;
if ($i == round($i) || $i < 1) {
return TRUE;
}
回答by JeroenEijkhof
You don't really need to use all three check and if you want a positive integer you might want to do the opposite of what is in your code:
你真的不需要使用所有三个检查,如果你想要一个正整数,你可能想要做与你的代码相反的事情:
if(is_numeric($i) && $i >= 0) { return true; }
Check S?ren's answer for more information concerning the difference between is_int()
and is_numeric()
检查S'仁的回答了有关之间区别的详细信息is_int()
和is_numeric()
回答by user1895505
Laravel 4.2 Validation rule for positive number
Laravel 4.2 正数验证规则
It takes only positive numbers including float values.
它只需要包括浮点值在内的正数。
public static $rules = array(
'field_name' => 'required|regex:/^\d*\.?\d*$/'
);
e.g:20,2.6,06
例如:20,2.6,06
回答by Mirko Pagliai
if(preg_match('/^[1-9]\d*$/',$i)) {
//Positive and > 0
}
回答by WebChemist
Rather than checking for int
OR string
with multiple conditions like:
而不是检查具有多个条件的int
OR string
,例如:
if ( ctype_digit($i) || ( is_int($i) && $i > 0 ) )
{
return TRUE;
}
you can simplify this by just casting the input to (string)
so that the one ctype_digit
call will check both string
and int
inputs:
您可以通过将输入强制转换为来简化此操作,(string)
以便一次ctype_digit
调用将同时检查string
和int
输入:
if( ctype_digit( (string)$i ) )
{
return TRUE;
}