基本上我想知道是否有办法缩短类似这样的东西:
if ($variable == "one" || $variable == "two" || $variable == "three")
以这种方式编写代码,可以在不重复变量和运算符的情况下,将变量与多个值进行测试或比较。
例如,以下示例可能会有所帮助:
if ($variable == "one" or "two" or "three")
或者任何导致输入量减少的事情。
基本上我想知道是否有办法缩短类似这样的东西:
if ($variable == "one" || $variable == "two" || $variable == "three")
以这种方式编写代码,可以在不重复变量和运算符的情况下,将变量与多个值进行测试或比较。
例如,以下示例可能会有所帮助:
if ($variable == "one" or "two" or "three")
或者任何导致输入量减少的事情。
in_array()
是我所使用的函数
if (in_array($variable, array('one','two','three'))) {
&&
的情况? - Imnotapotato不需要构建数组:
if (strstr('onetwothree', $variable))
//or case-insensitive => stristr
twothr
,这将返回 true,因此添加“分隔符”可能会很方便:if (stristr('one/two/three', $variable))//or comma's or somehting else
strstr
而第二次使用了stristr
。它们有什么区别? - vertigoelectricstrstr
查找一个_完全匹配_的字符串(区分大小写)而 stristr
带有 i
则执行不区分大小写的比较。这是唯一的区别。是的,那个错误的拼写是打错了 :P - Elias Van Ootegem"/{$variable}/"
而不是$variable
。虽然可能会慢一些,但in_array
解决方案开始变得更加清晰。 - LSerni$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";
}
使用 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;
}
使用preg_grep
比使用in_array
更短更灵活:
if (preg_grep("/(one|two|three)/i", array($variable))) {
// ...
}
因为可选的i
模式修饰符(i不区分大小写)可以匹配大写和小写字母。