user8675722
user8675722

Reputation:

Execute code inside IF statement in all cases but one

What would be the right way to do this? For example:

if ($var1 == 'value1' && $var2 == 'value2') {
    //code2
    return;
} else {
    //code1
}
//code2

I was thinking of using keyword continue insided if but I would also like to know if there is a better way?

EDIT

To be more precise I am going to try explaining it better. $var1 is current logged in user's role and $var2 is role of user whose details (let's say email) are being inserted into table. code2 is part that always need to be executed and there are a lot of lines there and therefore I shouldn't duplicate it. code1 is part where I am informing user that he is supposed to verify his email address and I am inserting into table the same thing (that email is still not verified). There is only one case when this shouldn't happen and when email should be automatically verified upon adding and that case is when $var1 is ADMIN and $var2 is REGULAR USER. In all other cases, code1 should be executed.

Upvotes: 0

Views: 33

Answers (1)

Pavel Janicek
Pavel Janicek

Reputation: 14748

From your question

if ($var1 == 'value1' && $var2 == 'value2') {
    //code2
    return;
} else {
    //code1
}
//code2

That sounds to me that code2 should be executed no matter what. In that case, you have to switch the if statement:

if( $var1 != 'value1' || $var2 != 'value2'){
  code1();
}
code2();

The code2 will be always execute and in the case you need, the code1 will execute too

Upvotes: 2

Related Questions