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

梦想的初衷 提交于 2019-11-26 15:33:24

in_array() is what I use

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

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

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;
}

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.

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