0

Possible Duplicates:
php multiple if conditions
What is better ? Multiple if statements, or one if with multiple conditions

So I was working on a segment of code in which I ended up using two different styles of if statements. That got me wondering - which one is more efficient in PHP? Are there times when one might be better than the other, despite general differences (if present)? Is there a certain level of complexity where the benefits become clear (if close) or close (if originally clear)? Also, are there other benefits of one method over the other, other than aesthetic or subjective differences?

if ($value == 'someval') {
  if($otherval == 'someval') {
    // do stuff
  } else if ($otherval == 'otherval') {
    // do same stuff
  }
}

vs

if (($value == 'someval') && ($otherval == 'someval' || $thirdval == 'someval') {
  // do stuff
}

Note - I don't care what works for C# or Java or whatever other language, unless someone can show that they handle the construct exactly the same.

Community
  • 1
  • 1
Shauna
  • 9,495
  • 2
  • 37
  • 54
  • 2
    You forgot a ) at the end of your 2nd if-statement ;) – Fge May 17 '11 at 15:08
  • @Marc B and webbiedave - I saw both of those and felt that, since the PHP one was talking about how to solve a particular issue and why it wasn't working (not to mention is so poorly worded that it's barely even a valid question), and the second one is talking about Java (and since Java != PHP in terms of efficiency and optimization), they aren't valid duplicates IMO. – Shauna May 17 '11 at 16:34
  • 1
    @Ash - I did do a search and came up empty. Even the lists of suggestions SO provides based on title and tags didn't really provide anything. – Shauna May 17 '11 at 16:35

3 Answers3

3

So long as you're executing the same code in each block (as you've indicated by your comments) then they'll both do the trick (and no, there's really not much of a performance difference).

However, typically it's not the case that you'd execute the same code both ways, so logically the first block is actually different from the second in that case. Here's an example:

if($value == 'someval') {
   if($otherval == 'someval') {
     doSomething();
   }
   else if ($otherval == 'otherval') {
     doSomethingElse();
   }
}

versus:

if(($value == 'someval') && ($otherval == 'someval' || $otherval == 'otherval')) {
   //we now still need to evaluate $otherval in order to determine which func to execute...
   //this adds bloat...
   if($otherval == 'someval') {
     doSomething();
   }
   else if ($otherval == 'otherval') {
     doSomethingElse();
   }
}

So as you can see in the case above the second block is actually less efficient than the first.

Brian Driscoll
  • 19,373
  • 3
  • 46
  • 65
2

There is no real difference, you should use whichever is more readable.

matt b
  • 138,234
  • 66
  • 282
  • 345
0

Nested or not nested if-blocks?

Community
  • 1
  • 1
CristiC
  • 22,068
  • 12
  • 57
  • 89