简体   繁体   中英

How can I combine multiple operator statements into one statement in PHP?

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

The best way I can think of is using in_array() :

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

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

The short answer is no.

The long answer is: you can create an array of strings

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

and then do

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

If you have multiple exclusive conditions like that, switch syntax is pretty clean:

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

    // other conditions...

    default:
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM