Jump to content

Is there a way to clean up an if statement with many conditions?


ballhogjoni

Recommended Posts

you can use the switch function:

switch( $if )
{
    // same thing as if ( $condition == 'value' )
    case 'value':
          do this;
          break;
    case 'value2': 
    case 'value3':
         do that;
         break;
}

 

You can separate your conditions and have it broken down onto separate lines.

 

As my dad always said, "if it ain't broke don't fix it".

We'd have to see the actual code to know if there is a way to rewrite it using less conditions or a different structure.  If your goal is just to reduce the line length you can either

a) Use some temp variables to shorten the if -or-

b) Separate the conditions onto separate lines.

 

 

Eg, giving the original statement of:

if(condition1 && condition2 && (condition3 && condition4) || (condition5 && condition6) || (condition7 && condition8))

 

a)

$res1 = condition3 && condition4;
$res2 = condition5 && condition6;
$res3 = condition7 && condition8;

if(condition1 && condition2 && $res1 || $res2 || $res3)

 

 

b)

if(
condition1 
&& condition2 
&& (condition3 && condition4) 
|| (condition5 && condition6) 
|| (condition7 && condition8)
)

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.