Jump to content

[SOLVED] IF Statement using OR instead of Else If with AND involved?


Recommended Posts

I'm not sure if this is bad practise or not, but is it possible to do this:

 

<?php
if(x=='1' && y=='1' || x=='2' && y=='5')
{
  // Do This
}

 

Instead of

 

<?php
if(x=='1' && y=='1')
{
  // Do This
}
else if(x=='2' && y=='5')
{
  // Do This
}

 

I'd prefer the first method so that I am not duplicating code. I'm noticing that it looks like the code checks "|| x=='2'" and ignore's the &&  so that if x=='2' it runs, and ignores whatever y is equal to.

 

Is that intended?

 

Worst case scenario I'll just use included files to try and avoid reproducing a lot of code.

Stryves: Assuming the "Do This" code is the same, they're logically equivalent. However, the first is obviously nicer as it means you don't have to repeat that code.

 

The if statement your first presented is indeed valid - the && operator has a higher precedence than the || operator, so is evaluated first. See this manual page for more on precedence. All that said, i personally would prefer to add the extra brackets as it makes it easier to read and you or other people are less likely to mistake the purpose of the if statement. E.g.:

 

if( ($x=='1' && $y=='1') || ($x=='2' && $y=='5') )

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.