PHP嵌套Ifs与具有多个条件的Single If [英] PHP Nested Ifs vs Single If with Multiple Conditions

查看:137
本文介绍了PHP嵌套Ifs与具有多个条件的Single If的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复项:
PHP多个if条件
哪个更好?多个if语句,或者一个if具有多个条件

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

因此,我正在处理一段代码,最终使用了两种不同样式的if语句.这让我感到疑惑-在PHP中哪个更有效?尽管存在普遍差异(如果存在),但有时是否有人会比另一个更好?收益变得清晰(如果接近)或接近(如果最初清晰)会在某种程度上的复杂性吗?另外,除了美学或主观差异之外,一种方法相对于另一种方法还有其他好处吗?

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
}

注意-我不在乎什么适用于C#或Java或任何其他语言,除非有人可以证明他们对结构的处理完全相同.

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();
   }
}

与之相对:

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.

这篇关于PHP嵌套Ifs与具有多个条件的Single If的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆