php 如何检查一个整数是否在一个范围内?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5029409/
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
How to check if an integer is within a range?
提问by dynamic
Is there a way to test a range without doing this redundant code:
有没有办法在不执行此冗余代码的情况下测试范围:
if ($int>$min && $int<$max)
?
?
Like a function:
像一个函数:
function testRange($int,$min,$max){
return ($min<$int && $int<$max);
}
usage:
用法:
if (testRange($int,$min,$max))
?
?
Does PHP have such built-in function? Or any other way to do it?
PHP 有这样的内置函数吗?或者有其他方法可以做到吗?
采纳答案by alex
I don't think you'll get a better way than your function.
我不认为你会得到比你的函数更好的方法。
It is clean, easy to follow and understand, and returns the result of the condition (no return (...) ? true : false
mess).
它很干净,易于理解和理解,并返回条件的结果(没有return (...) ? true : false
混乱)。
回答by Mark Paspirgilis
Tested your 3 ways with a 1000000-times-loop.
用 1000000 次循环测试了您的 3 种方式。
t1_test1: ($val >= $min && $val <= $max)
: 0.3823 ms
t1_test1: ($val >= $min && $val <= $max)
: 0.3823 毫秒
t2_test2: (in_array($val, range($min, $max))
: 9.3301 ms
t2_test2: (in_array($val, range($min, $max))
: 9.3301 毫秒
t3_test3: (max(min($var, $max), $min) == $val)
: 0.7272 ms
t3_test3 (max(min($var, $max), $min) == $val)
::0.7272 毫秒
T1 was fastest, it was basicly this:
T1最快,基本上是这样的:
function t1($val, $min, $max) {
return ($val >= $min && $val <= $max);
}
回答by Lars Strojny
There is no builtin function, but you can easily achieve it by calling the functions min()
and max()
appropriately.
没有内置函数,但您可以通过调用函数min()
并max()
适当地轻松实现它。
// Limit integer between 1 and 100000
$var = max(min($var, 100000), 1);
回答by Luis Rosety
Most of the given examples assume that for the test range [$a..$b], $a <= $b, i.e. the range extremes are in lower - higher order and most assume that all are integer numbers.
But I needed a function to test if $n was between $a and $b, as described here:
大多数给定的示例假设对于测试范围 [$a..$b],$a <= $b,即范围极值处于较低 - 较高的顺序,并且大多数假设都是整数。
但是我需要一个函数来测试 $n 是否在 $a 和 $b 之间,如下所述:
Check if $n is between $a and $b even if:
$a < $b
$a > $b
$a = $b
All numbers can be real, not only integer.
There is an easy way to test.
I base the test it in the fact that ($n-$a)
and ($n-$b)
have different signs when $n is between $a and $b, and the same sign when $n is outside the $a..$b range.
This function is valid for testing increasing, decreasing, positive and negative numbers, not limited to test only integer numbers.
有一种简单的测试方法。
我基地测试的事实,($n-$a)
并($n-$b)
有不同的符号时,$ n是一个$和$ b之间,与相同的符号,当$ n为$ A .. $ B范围之外。
此函数适用于测试递增、递减、正负数,不限于测试整数。
function between($n, $a, $b)
{
return (($a==$n)&&($b==$n))? true : ($n-$a)*($n-$b)<0;
}
回答by Esa Lindqvist
I'm not able to comment (not enough reputation) so I'll amend Luis Rosety's answer here:
我无法发表评论(没有足够的声誉)所以我会在这里修改 Luis Rosety 的回答:
function between($n, $a, $b) {
return ($n-$a)*($n-$b) <= 0;
}
This function works also in cases where n == a or n == b.
此函数也适用于 n == a 或 n == b 的情况。
Proof: Let n belong to range [a,b], where [a,b] is a subset of real numbers.
证明:设 n 属于范围 [a,b],其中 [a,b] 是实数的子集。
Now a <= n <= b. Then n-a >= 0 and n-b <= 0. That means that (n-a)*(n-b) <= 0.
现在 a <= n <= b。然后 na >= 0 和 nb <= 0。这意味着 (na)*(nb) <= 0。
Case b <= n <= a works similarly.
情况 b <= n <= a 的工作原理类似。
回答by Krzysiu
There's filter_var()
as well and it's the native function which checks range. It doesn't give exactly what you want (never returns true), but with "cheat" we can change it.
还有filter_var()
,它是检查 range的本机函数。它并没有给出你想要的(永远不会返回真),但是我们可以通过“作弊”来改变它。
I don't think it's a good code as for readability, but I show it's as a possibility:
我认为就可读性而言,这不是一个好的代码,但我表明这是一种可能性:
return (filter_var($someNumber, FILTER_VALIDATE_INT, ['options' => ['min_range' => $min, 'max_range' => $max]]) !== false)
Just fill $someNumber
, $min
and $max
. filter_var
with that filter returns either boolean false when number is outside range or the number itself when it's within range. The expression (!== false
) makes function return true, when number is within range.
只需填写$someNumber
,$min
和$max
。filter_var
当数字超出范围时,该过滤器返回布尔值 false 或在范围内时返回数字本身。!== false
当数字在范围内时,表达式 ( ) 使函数返回 true。
If you want to shorten it somehow, remember about type casting. If you would use !=
it would be false for number 0 within range -5; +5 (while it should be true). The same would happen if you would use type casting ((bool)
).
如果您想以某种方式缩短它,请记住类型转换。如果您将使用!=
它,则对于 -5 范围内的数字 0 将是错误的;+5(虽然它应该是真的)。如果您使用类型转换 ( (bool)
),也会发生同样的情况。
// EXAMPLE OF WRONG USE, GIVES WRONG RESULTS WITH "0"
(bool)filter_var($someNumber, FILTER_VALIDATE_INT, ['options' => ['min_range' => $min, 'max_range' => $max]])
if (filter_var($someNumber, FILTER_VALIDATE_INT, ['options' => ['min_range' => $min, 'max_range' => $max]])) ...
Imagine that (from other answer):
想象一下(来自其他答案):
if(in_array($userScore, range(-5, 5))) echo 'your score is correct'; else echo 'incorrect, enter again';
If user would write empty value ($userScore = ''
) it would be correct, as in_array
is set here for default, non-strict more and that means that range creates 0
as well, and '' == 0
(non-strict), but '' !== 0
(if you would use strict mode). It's easy to miss such things and that's why I wrote a bit about that. I was learned that strict operators are default, and programmer could use non-strict only in special cases. I think it's a good lesson. Most examples here would fail in some cases because non-strict checking.
如果用户将写入空值 ( $userScore = ''
) 它将是正确的,正如in_array
此处设置的默认值,非严格更多,这意味着范围0
也会创建,并且'' == 0
(非严格),但是'' !== 0
(如果您使用严格模式)。很容易错过这样的事情,这就是我写一些关于它的原因。我了解到严格运算符是默认的,程序员只能在特殊情况下使用非严格运算符。我认为这是一个很好的教训。在某些情况下,这里的大多数示例都会因为非严格检查而失败。
Still I like filter_var and you can use above (or below if I'd got so "upped" ;)) functions and make your own callback which you would use as FILTER_CALLBACK
filter. You could return bool or even add openRange
parameter. And other good point: you can use other functions, e.g. checking range of every number of array or POST/GET values. That's really powerful tool.
我仍然喜欢 filter_var 并且你可以使用上面(或下面,如果我得到了如此“提升”;)) 函数并制作你自己的回调,你可以将它用作FILTER_CALLBACK
过滤器。您可以返回 bool 甚至添加openRange
参数。还有其他好处:您可以使用其他函数,例如检查每个数组或 POST/GET 值的范围。这真是一个强大的工具。
回答by Thom Wiggers
Using comparison operators is way, way faster than calling any function. I'm not 100% sure if this exists, but I think it doesn't.
使用比较运算符比调用任何函数要快得多。我不是 100% 确定这是否存在,但我认为它不存在。
回答by Peter
You could do it using in_array()
combined with range()
你可以in_array()
结合使用range()
if (in_array($value, range($min, $max))) {
// Value is in range
}
NoteAs has been pointed out in the comments however, this is not exactly a great solution if you are focussed on performance. Generating an array (escpecially with larger ranges) will slow down the execution.
注意正如评论中指出的那样,如果您专注于性能,这并不是一个很好的解决方案。生成数组(尤其是具有更大范围的数组)会减慢执行速度。