JGreig
JGreig

Reputation: 7559

Simple IF statement question

How can I simply the below if statements?

if ( isset(var1) & isset(var2) ) {

    if ( (var1 != something1) || (var2 != something2) ) {

        // ... code ...
    }

}

Seems like this could be condensed to only one IF statement but am not certain if I'd use an AND or OR

Upvotes: 1

Views: 266

Answers (8)

Amien
Amien

Reputation: 974

I think most of the examples above that have 1 IF may spit out an error if var1 or var2 is NOT set

(isset($var1) && isset($var2)) ? ($var1!='something1' && $var2!='something2') ? $go=TRUE : $go=FALSE : $go = FALSE;

if ($go){
    echo 'hello';
}

Upvotes: 0

Nick Dandoulakis
Nick Dandoulakis

Reputation: 43110

Another option:

if (isset(var1) && isset(var2)
&& !(var1 == something1 && var2 == something2)) {
   ...

Upvotes: 0

JohnB
JohnB

Reputation: 18972

if (isset(var1) && isset(var2) && ((var1 != something1) || (var2 != something2)))
{
  // ... code ...
}

Upvotes: 0

amphetamachine
amphetamachine

Reputation: 30595

It's a question of in what order your computer interprets boolean logic:

Take for example the following conditions:

A: False B: True

if you were to write if (A && B) what your computer actually does is think:

Is A true? No.

Well, A and B can't be true because A isn't true. Therefore this statement is false. [computer ignores the rest of the logic]

Because of this, when you evaluate the statement isset(var1) && ( (var1 != something1) || (var1 != something2) ) it first checks isset(var1) and if that's false, then it skips the rest of the condition, just like your double-if statement.

Upvotes: 1

Devon_C_Miller
Devon_C_Miller

Reputation: 16518

if ( isset(var1) && isset(var2) && ( (var1 != something1) || (var2 != something2) ) ) {

    // ... code ...
}

Upvotes: 0

froadie
froadie

Reputation: 83043

Boolean varsAreSets = isset(var1) & isset(var2); // or some other name that indicates what this is doing
Boolean someMeaningfulName = (var1 != something1) || (var2 != something2); // would suggest a meaningful name but don't know what this is accomplishing

if ( varsAreSets && someMeaningfulName ) { 
        // ... code ... 
} 

This makes the code very readable and helps you and whoever reads the code understand what these checks are actually doing.

Upvotes: 2

codaddict
codaddict

Reputation: 454980

You can do:

if(isset(var1) && isset(var2) && ( (var1 != something1) || (var1 != something2) ) ){
    //..code
}   

As a general example:

if( cond1 && cond2 ) {
 if( cond3 || cond4) {
   // ...code..
 }
}

The code will be executed only when both cond1 and cond2 are true and either of cond3 or cond3 is true.

Upvotes: 1

Matt Ball
Matt Ball

Reputation: 359786

if (isset(var1) && ((var1 != something1) || (var1 != something2)))
    // ... code ...
}

You would use an and because you can only get to the // ... code ... part if both if-statements are true.

Upvotes: 1

Related Questions