2013-05-02 44 views
15

基本上我不知道是否有縮短這樣的一種方式:在PHP中,是否有一種簡單的方法將變量與多個值進行比較?

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

以這樣的方式,變量可以根據其進行測試或多個值進行比較,不用每次都重複的變量和操作員。

例如,沿此線的東西可能有幫助:

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

或任何導致更少的打字。

+0

我發現後,我意識到。當然,謝謝你的提示! – vertigoelectric 2013-05-02 19:08:18

回答

29

in_array()是我用

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

對我而言總是太快John Conde:P – brbcoding 2013-05-02 19:08:51

+2

我在發佈我的問題後意識到這一點。猜猜我跳過了槍。這是一個相當輝煌的解決方案,在一次比較幾件事情時特別有用。謝謝。一旦網站允許我接受它。它說我必須等待。 – vertigoelectric 2013-05-02 19:09:19

+1

@brbcoding,我仍然感謝你的努力。 – vertigoelectric 2013-05-02 19:10:46

0
$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";   
} 
4

而不需要構建一個數組:

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

當然,從技術上講,這將如果變量是twothr返回true,因此增加「分隔符」可能會得心應手:

if (stristr('one/two/three', $variable))//or comma's or somehting else 
+0

我認爲你有一個錯字,並打算說「twothr」而不是「thothr」,但顯然我知道你的意思。無論如何,這是另一個很好的策略,事實上,它更短。我注意到你第一次使用'strstr',第二次使用'stristr'。有什麼不同? – vertigoelectric 2013-05-02 19:42:01

+0

'strstr'查找_exact_字符串匹配(CaseSensitive)''stristr'與'i'執行不區分大小寫的比較。這是唯一的區別。是的,那個垃圾是一個錯字:P – 2013-05-02 19:45:00

+0

啊,好吧。這就是我認爲的不同之處。此外,'thwothr'仍然是一個錯字XD – vertigoelectric 2013-05-02 21:39:41

0

隨着開關殼體

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))) { 
    // ... 
} 

由於可選ipattern modifier nsensitive)可以匹配兩個上部和下部殼體字母。

相關問題