Question

If I want to create an if statement with 2 variables:

if ($variable1 && $variable2) {
    // Do something
}

And then add another if statement below with only the first variable, how would I do it? Do I only include the one variable like this:

else if ($variable1) {
     // Do something
}

Or do I need to specify that the first variable is true, not the second? If so, is this correct?

if ($variable1 && !$variable2) {
    // Do something
}
Was it helpful?

Solution

Go for:

if ($variable1 && $variable2) {
    // Do something
}

else if ($variable1) {
     // Do something
}

the reason is for example if you write like this :

the following is wrong approach

if ($variable1) {
        // if u have two variables $variable1 and $variable2
        // and you want to validate both but if the $variable1 contains
       //  nonzero value it will never go to the else part
    }

    else if ($variable1 && $variable2) {
         // Do something
    }

now basically

else if ($variable1) {
     // Do something
}

and

 else  if ($variable1 && !$variable2) {
        // Do something
    }

are same.you can use any of them if you are not toooo much concerned about the performance.

OTHER TIPS

else if ($variable1) {
     // Do something
}

is enough. Since the first if-statement will fail, it will evaluate the else if as a new statement

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top