有没有一种快速方法来检查变量是否属于集合?

发布于 2024-09-08 05:41:24 字数 183 浏览 0 评论 0 原文

我有一个表单,我需要检查输入是否属于 enum(0,1,2,3,..,n) 有没有一种简单的方法来检查我的变量是否属于集合 [0:n] ?或者我必须写出每个条件(基本上n<10,所以它是可行的,但不那么实用......)?

如果没有本地函数可以做到这一点,你能给我一个关于如何为此创建一个函数的提示吗?

谢谢 :)

I have a form and I need to check if a input belongs to enum(0,1,2,3,..,n)
Is there a simple way to check if my variable belongs to the set [0:n] ? Or do I have to write each condition (basically n<10, so it's feasible but not that practicle...)?

If there ain't native function to do that, could you give me a hint on how to make a function for this?

Thanks :)

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

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

发布评论

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

评论(3

寄居人 2024-09-15 05:41:24

您可以使用 range() 的组合和 in_array()

例子:

$number = 5;
$set = range(0, 10);
if (in_array($number, $set))
{
    //
}

You can use a combination of range() and in_array().

Example:

$number = 5;
$set = range(0, 10);
if (in_array($number, $set))
{
    //
}
心奴独伤 2024-09-15 05:41:24
$set = range(0,n);
if (in_array ($value, $set)) {
    print "IS IN ARRAY!";
}

这适用于 0 到 n 的范围
如果你想制作特定范围。 fe 0,1,3,7,你可以使用

$set = array(0,1,3,7...);
$set = range(0,n);
if (in_array ($value, $set)) {
    print "IS IN ARRAY!";
}

This is true for range from 0 to n
If you want to make specific range. f.e. 0,1,3,7, you can use

$set = array(0,1,3,7...);
陌若浮生 2024-09-15 05:41:24

您可以创建 范围 并运行 in_array,但这可能对性能不利。 PHP 将在内部最终循环遍历您提供的数字以创建一个全新的(可能很大)数组,然后再次循环遍历该数组以查看 X 是否在某处。这比简单的“是否在这些数字之内”检查所需的工作量要多得多。

坚持这两个条件可能是最好的方法,特别是因为它会更具可读性。如果出于某种原因,您确实需要一个辅助函数,您也可以创建一个辅助函数。

function is_within_inclusive($x, $start, $end) {
    return $x >= $start && $x <= $end;
}

但是,如果您已经定义了范围,无论如何,出于其他原因, in_array 似乎没问题。

You could make the range and run in_array, but that probably wouldn't be great for performance. PHP would internally end up looping through the numbers you provided to create a brand new (potentially huge) array, and then loop through the array all over again to see if X is in there somewhere. That's a lot more work than necessary for a simple "is it within these numbers" check.

Sticking to the two conditions is probably the best way to go, especially since it'd be much more readable. You can also make a helper function if this is, for some reason, really getting to you.

function is_within_inclusive($x, $start, $end) {
    return $x >= $start && $x <= $end;
}

But if you already have the range defined, anyway, for other reasons, in_array seems fine.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文