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".

Link to comment
Share on other sites

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

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.