In PHP, is there a short way to compare a variable

2019-01-07 00:01发布

问题:

Basically what I'm wondering if there is a way to shorten something like this:

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

in such a way that the variable can be tested against or compared with multiple values without repeating the variable and operator every time.

For example, something along the lines of this might help:

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

or anything that results in less typing.

回答1:

in_array() is what I use

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


回答2:

Without the need of constructing an array:

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

Of course, technically, this will return true if variable is twothr, so adding "delimiters" might be handy:

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


回答3:

$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:

With switch case

switch($variable){
 case 'one': case 'two': case 'three':
   //do something amazing here
 break;
 default:
   //throw new Exception("You are not worth it");
 break;
}


回答5:

Using preg_grep could be shorter and more flexible than using in_array:

if (preg_grep("/(one|two|three)/i", array($variable))) {
  // ...
}

Because the optional i pattern modifier (insensitive) can match both upper and lower case letters.