如何在PHP中将多个运算符语句组合成一个语句?

时间:2011-09-30 22:35:01

标签: php

例如,我总是做if($word=='hi' || $word=='test' || $word=='blah'...之类的事情 这可能会变得很长。如果有一种简单的方法将这些语句组合成一个语句?

3 个答案:

答案 0 :(得分:3)

我能想到的最好方法是使用in_array()

$possible = array('hi', 'test', 'blah');
if (in_array($word, $possible)) { ...

http://php.net/manual/en/function.in-array.php

答案 1 :(得分:0)

简短的回答是否定的。

答案很长:你可以创建一个字符串数组

$words = array('hi', 'test', 'blah');

然后再做

if (array_search($word, $words) !== false) do smth.

答案 2 :(得分:0)

如果您有多个这样的独有条件,switch语法非常简洁:

switch ($word) {
    case 'hi':
    case 'test':
    case 'blah':
        // Do something useful.
        break;

    // other conditions...

    default:
}