Jump to content

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


Stryves

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') )

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.