Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to shorten `if-statement`

I have an if statement in my foreach loop. The condition is about 125 characters long. Are there other ways to shorten this?

if ($col == 'foo' || $col == 'bar' || $col == 'baz' || $col == 'fubar' || $col == 'spam' || $col == 'eggs') {
    continue;
} 

NOTE: sorry for the confusion on the condition values guys, 'a', 'b', ... were meant to be various strings.

like image 775
Burning Crystals Avatar asked Dec 20 '22 03:12

Burning Crystals


2 Answers

Store all elements in single dimension array first, in your case this will be look like:

$array = array('a','b','c','d','e','f');

Then use php in built function in_array() to check whether $col exists in array, in your this looks like:

in_array($col, $array);

Entire code:

$array = array('a','b','c','d','e','f');
if(in_array($col, $array)) {
    continue;
}
like image 60
Sagar Avatar answered Jan 02 '23 01:01

Sagar


I would use an array:

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

But be aware than this is not really an optimisation, more of a readability enhancement. There's nothing wrong with your previous statement.

like image 42
Scopey Avatar answered Jan 02 '23 01:01

Scopey