3

i wonder if its possible to combine both operators (OR and AND) in one if statement like this.

if($apple==1 && $orange==2 || cake==0)

What i want to state is: if apple equals 1 AND orange equals 2, OR cake equals 0 then do this. In other words, i need apple and orange to equal the numbers stated above OR cake to equal 0.

Is this expression correct? If not, whats the simplest way to do it?

Thank you.

3 Answers 3

12

You should use inner parentheses for precedence ..

The reason is.. the first condition that was wrapped inside the parentheses will be evaluated as a block

As the other user mentioned, && has higher precedence over the || there is no need for the parentheses , but say if your if statement goes on like this..

if($apple==1 || $orange==2 && cake==0) 

Then you need to go on with ..

if(($apple==1 || $orange==2) && cake==0)

Sidenote : Always its a good practice to use parantheses...

Sign up to request clarification or add additional context in comments.

5 Comments

Why "should" parenthesis be used like that? They are both left-ward associative operators and && has a higher precedence.
You should use parentheses in your case because && has higher precedence than ||
@user2864740 Sorry. I did mistake. In this case you don't need parentheses because && has higher precedence than ||. So your answer is correct
The first two paragraphs are still not in agreement with the third. There is no "reason" if if there is "no need". It is one or the other.
How would you tell if $orange, $cake, or both triggered the match?
5

The expression

$apple==1 && $orange==2 || $cake==0

is equivalent to

($apple==1 && $orange==2) || $cake==0

because && has a higher precedence. As such, it means "when apple is 1 and orange is 2, or cake is 0".

While parenthesis can be used - and can make code more readable - they are not required in this case. However, parenthesis would be required when writing

$apple==1 && ($orange==2 || $cake==0)

which means "when apple is 1 and it is the case that either orange is 2 or cake is 0".

Comments

0

In your case the clause should look like following.

if(($apple==1 && $orange==2) || cake==0)

1 Comment

there is no point to post 2 similar answer as someone already posted. this is stupidness action.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.