在PHP中,是否有一种简便的方法来将一个变量与多个值进行比较?

24

基本上我想知道是否有办法缩短类似这样的东西:

if ($variable == "one" || $variable == "two" || $variable == "three")

以这种方式编写代码,可以在不重复变量和运算符的情况下,将变量与多个值进行测试或比较。

例如,以下示例可能会有所帮助:

if ($variable == "one" or "two" or "three")

或者任何导致输入量减少的事情。


我发帖后意识到了这一点。当然,感谢你的提示! - vertigoelectric
5个回答

45

in_array() 是我所使用的函数

if (in_array($variable, array('one','two','three'))) {

3
John Conde总是太快了,让我跟不上:P - brbcoding
2
我在发布问题后才意识到这一点。看来我有些心急了。这是一个相当出色的解决方案,特别是在同时比较多个事物时非常有帮助。谢谢你。一旦网站允许我这样做,我会接受它。它说我必须等待。 - vertigoelectric
1
@brbcoding,我仍然感谢你的努力。 - vertigoelectric
2
如果($variable)是以下之一:['one','two','three'],则执行以下操作: - Code4R7
你会如何处理使用 AND && 的情况? - Imnotapotato

4

不需要构建数组:

if (strstr('onetwothree', $variable))
//or case-insensitive => stristr

当然,从技术上讲,如果变量是 twothr,这将返回 true,因此添加“分隔符”可能会很方便:
if (stristr('one/two/three', $variable))//or comma's or somehting else

我认为你打错了字,应该是“twothr”而不是“thothr”,但显然我知道你的意思。无论如何,这是另一种不错的策略,事实上,甚至更短。我注意到你第一次使用了strstr而第二次使用了stristr。它们有什么区别? - vertigoelectric
strstr 查找一个_完全匹配_的字符串(区分大小写)而 stristr 带有 i 则执行不区分大小写的比较。这是唯一的区别。是的,那个错误的拼写是打错了 :P - Elias Van Ootegem
啊,好的。这就是我认为的区别。而且“thwothr”仍然是一个错字XD。 - vertigoelectric
@vertigoelectric:啊,糟糕...今天我似乎无法集中精力 ;) - Elias Van Ootegem
2
不幸的是,这还不够:这仍然会批准像“ree”或“wo”这样的值。您需要使用"/{$variable}/"而不是$variable。虽然可能会慢一些,但in_array解决方案开始变得更加清晰。 - LSerni
@LSerni:在这种情况下,需要一个像'/one/two/three/'这样的字符串,以便第一个和最后一个也适合。 - jimasun

1
$variable = 'one';
// ofc you could put the whole list in the in_array() 
$list = ['one','two','three'];
if(in_array($variable,$list)){      
    echo "yep";     
} else {   
    echo "nope";        
}

0

使用 switch case

switch($variable){
 case 'one': case 'two': case 'three':
   //do something amazing here
 break;
 default:
   //throw new Exception("You are not worth it");
 break;
}

0

使用preg_grep比使用in_array更短更灵活:

if (preg_grep("/(one|two|three)/i", array($variable))) {
  // ...
}

因为可选的i模式修饰符i不区分大小写)可以匹配大写和小写字母。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接