In PHP, is there a short way to compare a variable to multiple values?

拥有回忆 提交于 2019-11-26 04:28:24

问题


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.



来源:https://stackoverflow.com/questions/16345833/in-php-is-there-a-short-way-to-compare-a-variable-to-multiple-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!