What is the best way to use different logical operators in the same condition? [closed]

-3

I need to use two different logical operators in same condition . How to do it right?

I did it this way:

if($planohabilitargestao!="1000" || $planohabilitargestao!="200" || $planohabilitargestao!="10000" && $usuario=="")

Even if the variable $planohabilitargestao is equal to 1000, 200 and 10000 the condition is executed.

Do you have separate equal operators with parentheses?

    
asked by anonymous 29.03.2016 / 16:08

1 answer

2

Operators have equal precedence in mathematics, and the && operator, which is a AND , has more precedence than the || operator, which is a OR . Both have left-to-right associativity, so when operators have the same precedence, the first sub-expression will be executed first.

In this example there is && , with this sub-expression being executed first of all according to the precedence of operators, then $planohabilitargestao != "10000" && $usuario == "" is the first operation to be performed to later relate to the other || . I understand that this is not what you want.

The solution to this is to use parentheses by changing precedence, since this () operator has higher precedence than the others. Just do this:

($planohabilitargestao != "1000" || $planohabilitargestao != "200" || $planohabilitargestao != "10000) && $usuario == ""

Now the expression of && first has the final result of the expression that is in parentheses, so all || operators are executed first, and then the result is used as the% co_operator. >

On the other hand it may be (after editing) that you just want this:

$planohabilitargestao != "1000" && $planohabilitargestao != "200" && $planohabilitargestao != "10000 && $usuario == ""

At least that's what I "guessed" I wanted, I hope I got it right. I still try other options if the problem is better defined.

Precedence table .

    
29.03.2016 / 16:19