PHP 嵌套 If 与具有多个条件的单个 If
因此,我正在编写一段代码,最终我使用了两种不同样式的 if 语句。这让我想知道 - PHP 中哪一个更高效?尽管存在普遍差异(如果存在),有时是否会出现一个人比另一个人更好的情况?是否存在一定程度的复杂性,使得收益变得清晰(如果接近)或接近(如果最初清晰)?此外,除了审美或主观差异之外,一种方法相对于另一种方法还有其他好处吗?
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 或任何其他语言,除非有人可以证明他们以完全相同的方式处理构造。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(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:
versus:
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.
嵌套或不嵌套 if 块?
Nested or not nested if-blocks?