if 和 elseif 有什么区别? [英] What's the difference between if and elseif?

查看:57
本文介绍了if 和 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';
    }
?>

^^^和这个有区别吗:

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.

这篇关于if 和 elseif 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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