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.
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.
There is no real difference, you should use whichever is more readable.
Nested or not nested if-blocks?
精彩评论