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.

+3


source to share


4 answers


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

      

+6


source


I would use an array:

if(in_array($col, ['a','b','c','d','e','f'])) {
    continue;
}

      



But keep in mind that this is not really an optimization, but rather an improvement in readability. There is nothing wrong with your previous statement.

+2


source


I would use the fact that there is usually ascii, so you can do something like

 if ($col >= 'a' && $col <='f') {
    continue;
}

      

+2


source


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()

.

0


source







All Articles