如何检查一个整数是否在一个范围内?

发布于 2024-10-18 06:12:16 字数 358 浏览 2 评论 0原文

有没有办法在不执行以下冗余代码的情况下测试范围:

if ($int>$min && $int<$max)

就像一个函数:

function testRange($int,$min,$max){
    return ($min<$int && $int<$max);
}

用法:

if (testRange($int,$min,$max)) 

PHP有这样的内置函数吗?或者有其他方法可以做到吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

不再让梦枯萎 2024-10-25 06:12:16

用 1000000 次循环测试了你的 3 种方法。

t1_test1: ($val >= $min && $val <= $max): 0.3823 ms

t2_test2: (in_array($val, range($min, $max ) )): 9.3301 ms

t3_test3: (max(min($var, $max), $min) == $val): 0.7272 ms

T1 是最快的,基本上是这样的:

function t1($val, $min, $max) {
  return ($val >= $min && $val <= $max);
}

Tested your 3 ways with a 1000000-times-loop.

t1_test1: ($val >= $min && $val <= $max): 0.3823 ms

t2_test2: (in_array($val, range($min, $max)): 9.3301 ms

t3_test3: (max(min($var, $max), $min) == $val): 0.7272 ms

T1 was fastest, it was basicly this:

function t1($val, $min, $max) {
  return ($val >= $min && $val <= $max);
}
×纯※雪 2024-10-25 06:12:16

我认为你不会得到比你的功能更好的方法。

它很干净,易于遵循和理解,并返回条件的结果(没有 return (...) ? true : false 混乱)。

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).

网名女生简单气质 2024-10-25 06:12:16

没有内置函数,但您可以通过适当调用函数 min()max() 轻松实现。

// Limit integer between 1 and 100000
$var = max(min($var, 100000), 1);

There is no builtin function, but you can easily achieve it by calling the functions min() and max() appropriately.

// Limit integer between 1 and 100000
$var = max(min($var, 100000), 1);
哭了丶谁疼 2024-10-25 06:12:16

大多数给定的示例假设对于测试范围 [$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.

有一种简单的测试方法。
我进行测试的基础是,当 $n 在 $a 和 $ 之间时, ($n-$a)($n-$b) 有不同的符号b,当 $n 超出 $a..$b 范围时,符号相同。
该函数对测试递增、递减、正负数均有效,不限于仅测试整数。

function between($n, $a, $b)
{
    return (($a==$n)&&($b==$n))? true : ($n-$a)*($n-$b)<0;
}

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:

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.

function between($n, $a, $b)
{
    return (($a==$n)&&($b==$n))? true : ($n-$a)*($n-$b)<0;
}
戴着白色围巾的女孩 2024-10-25 06:12:16

我无法发表评论(没有足够的声誉),所以我将在这里修改 Luis Rosety 的答案:

function between($n, $a, $b) {
    return ($n-$a)*($n-$b) <= 0;
}

此函数也适用于 n == a 或 n == b 的情况。

证明:
令 n 属于范围 [a,b],其中 [a,b] 是实数的子集。

现在 a <= n <= b。那么 na >= 0 且 nb <= 0。这意味着 (na)*(nb) <= 0。

情况 b <= n <= a 的工作原理类似。

I'm not able to comment (not enough reputation) so I'll amend Luis Rosety's answer here:

function between($n, $a, $b) {
    return ($n-$a)*($n-$b) <= 0;
}

This function works also in cases where n == a or n == b.

Proof:
Let n belong to range [a,b], where [a,b] is a subset of real numbers.

Now a <= n <= b. Then n-a >= 0 and n-b <= 0. That means that (n-a)*(n-b) <= 0.

Case b <= n <= a works similarly.

凌乱心跳 2024-10-25 06:12:16

还有 filter_var(),它是检查范围的本机函数。它并没有给出你想要的(永远不会返回true),但是通过“cheat”我们可以改变它。

我认为就可读性而言这不是一个好的代码,但我表明它是一种可能性:

return (filter_var($someNumber, FILTER_VALIDATE_INT, ['options' => ['min_range' => $min, 'max_range' => $max]]) !== false)

只需填写 $someNumber$min$max.使用该过滤器的 filter_var 当数字超出范围时返回布尔值 false,或者当数字在范围内时返回数字本身。当数字在范围内时,表达式 (!== false) 使函数返回 true。

如果你想以某种方式缩短它,请记住类型转换。如果您使用 != ,则对于 -5 范围内的数字 0 将为 false; +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]])) ...

想象一下(来自其他答案):

if(in_array($userScore, range(-5, 5))) echo 'your score is correct'; else echo 'incorrect, enter again';

如果用户写入空值($userScore = ''),那么它将是正确的,因为in_array在这里设置为默认值,非-更严格,这意味着范围也会创建 0 ,并且 '' == 0 (非严格),但是 '' !== 0 code> (如果您使用严格模式)。人们很容易错过这些事情,这就是为什么我写了一些相关内容。 我了解到严格运算符是默认的,程序员只能在特殊情况下使用非严格。我认为这是一个很好的教训。这里的大多数示例在某些情况下都会失败,因为检查不严格。

我仍然喜欢filter_var,您可以使用上面(或下面,如果我得到了如此“升级”;))函数并创建您自己的回调,您可以将其用作FILTER_CALLBACK过滤器。您可以返回 bool 甚至添加 openRange 参数。还有其他好处:您可以使用其他功能,例如检查每个数字的范围数组或 POST/GET 值。这确实是一个非常强大的工具。

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.

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.

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)).

// 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.

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.

白首有我共你 2024-10-25 06:12:16

您可以使用 in_array() 结合 range()

if (in_array($value, range($min, $max))) {
    // Value is in range
}

注意 正如评论中所指出的,这并不完全是一个如果您注重性能,这是一个很好的解决方案。生成数组(尤其是范围较大的数组)会减慢执行速度。

You could do it using in_array() combined with range()

if (in_array($value, range($min, $max))) {
    // Value is in range
}

Note As 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.

世态炎凉 2024-10-25 06:12:16

使用比较运算符比调用任何函数要快得多。我不能百分百确定这是否存在,但我认为它不存在。

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.

听你说爱我 2024-10-25 06:12:16

一种可能性(不是解决方案):

$mysqli->query("SELECT $value BETWEEN $min and $max as test")->fetch_object()->test;

One possibility (not a solution) :

$mysqli->query("SELECT $value BETWEEN $min and $max as test")->fetch_object()->test;
一身软味 2024-10-25 06:12:16

这是对 @Mark Paspirgilis 提供的答案的扩展,允许可选择的包含并返回布尔响应。

public function between($p_value, $p_min, $p_max, $p_inclusive=0) {
  ## 0 = all inclusive; -1 = left inclusive; 1 = right inclusive
  if ($p_inclusive == -1) {
    return (bool)($p_value >= $p_min && $p_value < $p_max);
  }
  else if ($p_inclusive == 1) {
    return (bool)($p_value > $p_min && $p_value <= $p_max);
  }
  else {
    return (bool)($p_value >= $p_min && $p_value <= $p_max);
  }
} # END FUNCTION between

This is an expansion on the answer provided by @Mark Paspirgilis, allows for selectable inclusion and returns a Boolean response.

public function between($p_value, $p_min, $p_max, $p_inclusive=0) {
  ## 0 = all inclusive; -1 = left inclusive; 1 = right inclusive
  if ($p_inclusive == -1) {
    return (bool)($p_value >= $p_min && $p_value < $p_max);
  }
  else if ($p_inclusive == 1) {
    return (bool)($p_value > $p_min && $p_value <= $p_max);
  }
  else {
    return (bool)($p_value >= $p_min && $p_value <= $p_max);
  }
} # END FUNCTION between
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文