Pek*_*ica 98
一种优雅的方式是动态构建阵列并使用in_array()
:
if (in_array($var, array("abc", "def", "ghi")))
Run Code Online (Sandbox Code Playgroud)
该switch
声明也是另一种选择:
switch ($var) {
case "abc":
case "def":
case "hij":
echo "yes";
break;
default:
echo "no";
}
Run Code Online (Sandbox Code Playgroud)
Tok*_*okk 41
if($var == "abc" || $var == "def" || ...)
{
echo "true";
}
Run Code Online (Sandbox Code Playgroud)
我想,使用"或"代替"和"会有所帮助
Sha*_*ngh 11
你可以使用php的in_array函数
$array=array('abc', 'def', 'hij', 'klm', 'nop');
if (in_array($val,$array))
{
echo 'Value found';
}
Run Code Online (Sandbox Code Playgroud)
Kin*_*nch 11
不知道,为什么要使用&&
.这是一个更容易的解决方案
echo in_array($var, array('abc', 'def', 'hij', 'klm', 'nop'))
? 'yes'
: 'no';
Run Code Online (Sandbox Code Playgroud)
小智 6
很抱歉复活这个,但我偶然发现了它并相信它增加了这个问题的价值。
在PHP 8.0.0^中,您现在可以使用匹配表达式,如下所示:
<?php
echo match ($var) {
'abc','def','hij','klm' => 'true',
};
?>
//echos 'true' as a string
Run Code Online (Sandbox Code Playgroud)
您可以使用布尔运算符或:
if($var == 'abc' || $var == 'def' || $var == 'hij' || $var == 'klm' || $var == 'nop'){
echo "true";
}
Run Code Online (Sandbox Code Playgroud)
你可以试试这个:
<?php
echo (($var=='abc' || $var=='def' || $var=='hij' || $var=='klm' || $var=='nop') ? "true" : "false");
?>
Run Code Online (Sandbox Code Playgroud)
小智 5
我发现这个方法对我有用:
$thisproduct = "my_product_id";
$array=array("$product1", "$product2", "$product3", "$product4");
if (in_array($thisproduct,$array)) {
echo "Product found";
}
Run Code Online (Sandbox Code Playgroud)