Long If Condition or For Loop with If Condition?

463 Views Asked by At

Just wondering, but assuming you had maybe 10 different values to compare to X, would it be better to write one giant long if condition, or a for loop with an if-statement that returns true if x == value, and then false if the for loop finishes without returning true?

3

There are 3 best solutions below

0
On BEST ANSWER

The long if statement is going to be hard to read for humans and space consuming. It will be slightly faster however than the for loop, but that should't bother you.

A better way would be to make the for loop in a separate function that returns boolean value or storing the comparison values in an array and checking something like:

var array = [1,2,3,4,5]

if(array.contains(x))
{
    // x is one of the values
}
else
{
   // x is not in the values
}
0
On

Which programming language you are using? For Php Lets try this by using in_array() function of php.

 $arr_value = array("value1", "value2", "value3", "value4"); //set matching values

 if(in_array($original_value, $arr_value))
 {

  //true block

 }
 else
 {

  //false block

 }
0
On

Giant long if condition is not advisable because you may encounter a conflict on it. Instead use if else condition to solve your problem.