How to shorten `if-statement`
I have a statement if
in my foreach loop. The condition is about 125 characters long. Are there any other ways to shorten this?
if ($col == 'foo' || $col == 'bar' || $col == 'baz' || $col == 'fubar' || $col == 'spam' || $col == 'eggs') {
continue;
}
NOTE: I'm sorry for the confusion within the meaning of terms, guys 'a'
, 'b'
... had to be different lines.
source to share
First, store all the elements in an array with one dimension, in your case it will look like this:
$array = array('a','b','c','d','e','f');
Then use php in the built-in function in_array () to check if $ col exists in the array, this looks like:
in_array($col, $array);
Whole code:
$array = array('a','b','c','d','e','f');
if(in_array($col, $array)) {
continue;
}
source to share
Try something like this:
if (in_array($col, array('foo', 'bar', 'baz', 'fubar', 'spam', 'eggs'))
{
continue;
}
If you are using PHP 5.4+, you can make it a little more elegant:
if (in_array($col, ['foo', 'bar', 'baz', 'fubar', 'spam', 'eggs'])
{
continue;
}
If you need a strict comparison like in 'x' === $x
, add , true
to the call in_array()
.
source to share