if 和 elseif 有什么区别?

2022-01-21 00:00:00 if-statement conditional php

这应该是一个简单的问题.我有一个简单的 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';
    }
?>

^^^和这个有区别吗:

Is there a difference from ^^^ to this:

<?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.直到现在,我已经使用了第一部分(没有 elseif,只是一系列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.

谢谢!阿米特

推荐答案

是的.如果满足 if/else 控件中的条件,则将省略其余检查.else if 只是 else 内的嵌套 if

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';
}

但是在一系列if中,所有的都会被测试.

But in a series of ifs, 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.

相关文章