if和elseif有什么区别? [英] What's the difference between if and elseif?
问题描述
这应该是一个简单的问题。我有一个简单的if / else语句:
This should be a simple question. I have a simple if/else statement:
<?php
// TOP PICTURE DEFINITIONS
if ( is_page('english') ) {
$toppic = 'page1.png';
}
if ( is_page('aboutus') ) {
$toppic = 'page1.png';
}
if ( is_page('newspaper') ) {
$toppic = 'page1.png';
}
else {
$toppic = 'page1.png';
}
?>
与^^^有不同之处:
<?php
// TOP PICTURE DEFINITIONS
if ( is_page('english') ) {
$toppic = 'page1.png';
}
elseif ( is_page('aboutus') ) {
$toppic = 'page1.png';
}
elseif ( is_page('newspaper') ) {
$toppic = 'page1.png';
}
else {
$toppic = 'page1.png';
}
?>
我应该提到这是进入Wordpress的。直到现在,我已经使用了第一部分(没有其他,只是一系列'ifs'),它的确有效。我只是想知道区别是什么。
I should mention that this is going into Wordpress. And until now, I've used the first part (no elseif, just a series of 'ifs'), and it works. I was just curious to know what the difference was.
谢谢!
Amit
Thanks! Amit
推荐答案
是的。如果满足 if / else
控件中的条件,则将省略其余检查。 否则如果
只是一个嵌套的,如果
在 else
内!
Yes. If a condition in an if/else
control is satisfied, the rest of the checks will be omitted. else if
is just a nested if
inside an else
!
if ( is_page('english') ) { // if true, other statements are skipped
$toppic = 'page1.png';
}
elseif ( is_page('aboutus') ) {
$toppic = 'page1.png';
}
elseif ( is_page('newspaper') ) {
$toppic = 'page1.png';
}
else {
$toppic = 'page1.png';
}
但在一系列中如果
s,所有这些都将被测试。
But in a series of if
s, all of them will be tested.
if ( is_page('english') ) {
$toppic = 'page1.png';
}
if ( is_page('aboutus') ) { // will be tested no matter what the outcome
// of the previous if statement was
$toppic = 'page1.png';
}
if ( is_page('newspaper') ) { // the same here
$toppic = 'page1.png';
}
else {
$toppic = 'page1.png';
}
因此,如果您正在检查诸如数字奇偶校验的属性,无论是奇数还是偶数,如果一个人满意,你为什么还要费心去检查其他条件。这是浪费资源。因此,以下代码要好得多
So, if you're checking a property such as parity of a number, it's either odd or even, why do you want to bother checking other conditions if one is satisfied. It's a waste of resources. Therefore, the following code is much better
if(number_is_odd) {
}
else { // if it's not odd, it's even for sure
}
比
if(number_is_odd) {
}
if(!number_is_odd) {
}
因为前者检查条件一次而后者检查两次。具有两种以上状态的条件也是如此。
Because the former checks the condition once whilst the latter does it twice. The same thing goes for conditions with more than two states.
这篇关于if和elseif有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!