2011-04-08 84 views

回答

32
if($var == "abc" || $var == "def" || ...) 
{ 
    echo "true"; 
} 

使用「或」而不是「和」會在這裏幫助,我認爲

11

你可以使用in_array PHP

$array=array('abc', 'def', 'hij', 'klm', 'nop'); 

if (in_array($val,$array)) 
{ 
    echo 'Value found'; 
} 
84

一種優雅的方式是建立在動態數組,並使用in_array()的功能:

if (in_array($var, array("abc", "def", "ghi"))) 

switch statement也是一種替代方案:

switch ($var) { 
case "abc": 
case "def": 
case "hij": 
    echo "yes"; 
    break; 
default: 
    echo "no"; 
} 
+1

是啊,in_array()正是我怎麼會做它。 – 2011-04-08 11:07:54

+1

這就是我需要:)感謝上帝的Stackoverflow存檔;) – 2016-05-19 07:37:46

+1

我發誓在php3我曾經這樣做如果($ var =='abc'|'xyz'|'cbs') 也許它只是一個夢:p – nodws 2017-06-12 17:36:59

11

不知道,爲什麼要使用&&。 Theres更簡單的解決方案

echo in_array($var, array('abc', 'def', 'hij', 'klm', 'nop')) 
     ? 'yes' 
     : 'no'; 
4

您可以使用布爾運算符或:

if($var == 'abc' || $var == 'def' || $var == 'hij' || $var == 'klm' || $var == 'nop'){ 
    echo "true"; 
} 
3

你可以試試這個:

<?php 
    echo (($var=='abc' || $var=='def' || $var=='hij' || $var=='klm' || $var=='nop') ? "true" : "false"); 
?> 
-9

我不知道,如果是$ var是一個字符串,你想找到只有那些表達式,但在這裏它去任何一種方式。

嘗試使用的preg_match http://php.net/manual/en/function.preg-match.php

if(preg_match('abc', $val) || preg_match('def', $val) || ...) 
    echo "true" 
+7

-1哇!你知道你剛剛造成多少開銷嗎?好神,男人! – 2011-04-08 11:09:09

+0

更不用說在模式中缺少的分隔符。 – SOFe 2017-06-06 16:25:41

1

嘗試這段代碼:

$first = $string[0]; 
if($first == 'A' || $first == 'E' || $first == 'I' || $first == 'O' || $first == 'U') { 
    $v='starts with vowel'; 
} 
else { 
    $v='does not start with vowel'; 
} 
0

這將是良好的使用陣列和在環1比較每個值1。它有利於改變你的測試數組的長度。寫一個帶2個參數的函數,1個是測試數組,另一個是要測試的數值。

$test_array = ('test1','test2', 'test3','test4'); 
for($i = 0; $i < count($test_array); $i++){ 
    if($test_value == $test_array[$i]){ 
     $ret_val = true; 
     break; 
    } 
    else{ 
     $ret_val = false; 
    } 
} 
0

我發現這個方法爲我工作:

$thisproduct = "my_product_id"; 
$array=array("$product1", "$product2", "$product3", "$product4"); 
if (in_array($thisproduct,$array)) { 
    echo "Product found"; 
}