What's the difference between if and elseif?

2020-04-08 08:02发布

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

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.

Thanks! Amit

8条回答
够拽才男人
2楼-- · 2020-04-08 08:24

In your first block, every comparison in your block is executed. Also, toppic will always be assigned the value in is_page('newspaper') or the value in is_page('newspaper')'s else statement. This happens because the last if statment is always evaluated. Even if one of the previous if statements evaluated to true, you'll end up in the else block. To test this, try this code...

<?php
    // TOP PICTURE DEFINITIONS
    if ( is_page('english') ) {
        $toppic = 'english.png';
    }
    if ( is_page('aboutus') ) {
        $toppic = 'aboutus.png';
    }
    if ( is_page('newspaper') ) {
        $toppic = 'newspaper.png';
    }
    else {
        $toppic = 'finalelse.png';
    }
?>

You'll always end with either 'newspaper.png' or 'finalelse.png'.

查看更多
做个烂人
3楼-- · 2020-04-08 08:29
<?php
    if ( 3 > 1 ) {
        echo "This will be printed.";
    }
    if ( 3 > 2 ) {
        echo "This will be printed too.";
    }
    if ( 3 > 3 ) {
        echo "This will NOT be printed.";
    }
    else {
        echo "This WILL be printed.";
    }
?>

but with elseif:

<?php
    if ( 3 > 1 ) {
        echo "This will be printed.";
    }
    elseif ( 3 > 2 ) {   /* This condition will not be evaluated */
        echo "This will NOT be printed";
              // because it's on the ELSE part of the previous IF
    }   
    elseif ( 3 > 3 ) {   /* This condition will not be evaluated either */
        echo "This will NOT be printed.";
    }
    else {    /* This ELSE condition is still part of the first IF clause */
        echo "This will NOT be printed.";
    }
?>

So you should use ELSEIF, because otherwise $toppic will always result on either 'newspaper.png', wich should be right, or 'finalelse.png' wich could be right or wrong, because it will overwrite the previous conditional clauses.

I hope you'll find this helpful.

查看更多
登录 后发表回答