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.
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.
来源:https://stackoverflow.com/questions/16345833/in-php-is-there-a-short-way-to-compare-a-variable-to-multiple-values