What’s the difference between Isis and elseif?

Asked

Viewed 12,868 times

26

I wanted to know the difference between else and elseif in PHP, and when should I use one or the other.

6 answers

25


The else is not in condition to verify and is used at the end/after a series of if / elseif, as "general case".

The elseif, like the if, is used in cases where it is necessary to verify the authenticity of a condition. So instead of multiple if, is used n elseif, and in the end the general case within the else.

Example, if you have many conditions:

if ($a == 'hoje') { //fazer algo }
elseif ($a == 'amanhã') { // fazer algo diferente }
else { // todos os outros casos }

If the value of $a for hoje only the first condition is checked and the other lines will not be run.

If the value of $a for amanhã the first line gives false, he tests the second condition and gives true. Only the second condition is checked and the other lines will not be run.

If the value of $a for ontem the first two conditions fail (give false and it only runs the code of else.

Notes:

The elseif is very useful to avoid long checks since the conditions are excluded (if a der true the others are not even tested/run).

In cases of many conditions it may be better to use the switch as @Zuul said. But this structure if/elseif/else allows different checks on each condition, while the switch checks only one variable that can have different values.

Example that the switch cannot reproduce:

if ($a == 'hoje') { //fazer algo }
elseif ($a == 'amanhã' && $mes == 'janeiro') { // fazer algo diferente }
elseif ($a == 'hoje' && $diaSemana == 'segunda') { // fazer algo diferente }
else { // todos os outros casos }
  • 3

    Since @Sergio said that’s right Else has no condition, Else if is usually used when you want to create another condition besides top if.

  • 1

    Thank you for the reply!

  • Still in the translation elseif can be translated into the sentence (if not) while Else only for otherwise.

17

We can read in the documentation that:

elseif, as its name suggests, is a combination of if and else. Like the else, he extends a command if to execute a different instruction in the case of the if original come to be evaluated as FALSE.

However, as opposed to else, it will execute that alternative expression only if the conditional expression of the elseif is assessed as TRUE.

In short, elseif introduces new conditions in our control structure.


Example

if ($a > $b) {               // entra se verdadeiro
    echo "a é maior que b";
} else if ($a == $b) {        // entra se verdadeiro
    echo "a é igual a b";
} else {                     // se chegou aqui, vai sempre entrar
    echo "a é menor que b";
}


Practical application

This type of intermediate check is useful for cases where we need to check two or more conditions before reaching the value "by default".

Note that when the checks are many, the if~elseif~else ends up being inefficient, making it preferable to use a control structure switch().

See this related question that talks about the use of switch instead of multiple elseif which, although referring to Javascript, applies to PHP in terms of performance.


Conventions

In PHP, the else if can also be written as elseif, both are correctly declared and produce the intended effect. Note that the same is not true in other languages:

See on the Ideone.

  • Example:

    $a = $b = 1;
    if ($a > $b) {                // entra se verdadeiro
        echo "a é maior que b";
    } else if ($a == $b) {        // entra se verdadeiro
        echo "a é igual a b";
    } else {                      // se chegou aqui, vai sempre entrar
        echo "a é menor que b";
    }
    
    echo PHP_EOL;
    
    $a = ($b = 1)+1;
    if ($a > $b) {               // entra se verdadeiro
        echo "a é maior que b";
    } elseif ($a == $b) {        // entra se verdadeiro
        echo "a é igual a b";
    } else {                     // se chegou aqui, vai sempre entrar
        echo "a é menor que b";
    }
    
  • Exit:

    a é igual a b  
    a é maior que b
    

Heed, for each rule an exception, learn more details about the differences between elseif and else if in this question.


Warnings

It should be noted that the use of a else if does not have the same effect as multiple if in some cases. Taking an example of manipulation of the value used in the condition, one can illustrate the failure as follows:

See on the Ideone.

  • Example:

    /* Pretende-se apurar onde se encaixa o A
     * em relação a grupos de 10 para fazer algo,
     * neste exemplo um "echo", e depois incrementar A
     * para prosseguir.
     */
    $a = 20;
    
    if ($a>=1  AND $a<=20) {
        echo "A no primeiro grupo";
        $a++;
    }
    
    echo PHP_EOL;
    
    if ($a>=21  AND $a<=30) {
        echo "A no segundo grupo";
        $a++;
    }
    
  • Exit:

    A no primeiro grupo  // correto
    A no segundo grupo   // errado, A no primeiro grupo e depois queriamos prosseguir
    

Just one example, basic but reflecting the fact that with a else if this scenario would never happen because the second condition would never be evaluated.

And this brings us to the performance of the application:

// vai verificar
if ($a > $b) {
    echo "a é maior que b";
}

// vai verificar
if ($a == $b) {
    echo "a é igual a b";
}

// vai verificar
if ($a < $b) {
    echo "a é menor que b";
}

In short, the application will carry out all the conditions, even if you do not need them, and this is where the else if helps to deal with the issue, as after a condition evaluated for true, the rest are ignored thus avoiding the unnecessary consumption of resources!

9

Everyone has already explained well what it is. I will try to show otherwise.

if ($valor < 10) {
    $total += $valor
} elseif ($total < 20) {
    $total += $valor * 1.1;
} elseif ($total < 30) {
    $total += $valor * 1.2;
} else {
    $total += $valor * 1.3;
}

Look now:

if ($valor < 10) {
    $total += $valor
}
if ($total < 20) {
    $total += $valor * 1.1;
}
if ($total < 30) {
    $total += $valor * 1.2;
}
if ($total >= 30) {
    $total += $valor * 1.3;
}

In the first case only one if will be executed. The block of the if works on a short-circuit, That is, when one of its subblocks is executed, the others are no longer executed. They are exclusionary. Then the result of it will be according to the first block that the condition result in true. In the second example, they can all execute if each of them individually results in true. It might be your intention, but it doesn’t seem to be. In this case if the value is less than 10, it will run 3 times and generate a cumulative value that probably should not do.

Note that the opposite is also true. If you need all the ifs be evaluated Regardless of the outcome of the previous ones, they obviously need to be independent, they cannot form a single block. If in doubt, do a table test, with both using a value below 10. Any value below 30 will produce a wrong result when the ifs are independent.

When you use the elseif you create a unique structure that works in an integrated way.

Of course it is possible to use only if and else and get the same result, but it looks like it looks weird:

if ($valor < 10) {
    $total += $valor
} else {
    if ($total < 20) {
        $total += $valor * 1.1;
    } else {
        if ($total < 30) {
            $total += $valor * 1.2;
        } else {
            if ($total >= 30) {
                $total += $valor * 1.3;
            }
        }
    }
}

I put in the Github for future reference.

The way using the elseif can be seen as syntax sugar to the way with else with ifs nested. And it is an important one to keep your code sane, especially if you have many execution subblocks.

Interestingly I think it would be easier to understand if people first learned the elseif. Because the else can be interpreted as elseif (true). That is, if none of the above conditions are false, then try this one, which is always the last, and it will surely perform because the if is waiting for a true to execute, and in this case, it is guaranteed that the result is this.

Obviously it doesn’t make sense to have more than one else or have a else before a elseif, after all it is guaranteed that it will run if it gets to it and then the circuit will be closed and no other sub-block will even be evaluated.

If you already understand the switch can see the elseif similarly. Of course the elseif allows more powerful conditions, the case allows only equal comparison of a unique value. The elseif is short-Circuit, the case It’s not, if you don’t put a break, he will try to evaluate the others. But the constructions are similar. You use both if the comparisons are related. It makes no sense, even if it works, to put unrelated comparisons in the same block.

  • It is necessary to be careful in these cases because if the first if involve the other results the others will never be executed. For example if you put the if ($total < 30) and then the others, the other 2 would never be executed.

  • 1

    +1 for the "excluding"

6

Just to clarify if you still have doubts, this is the default if :

if (condicao) 
    { 
        procedimento
    }
    else
    {
        if (outra codicao) 
        { 
            outro procedimento
        }
        else 
        { 
            mais um procedimento
        }
    }

with the simplification of if Else would:

if (condicao) 
    { 
         procedimento
    }
    else if (outra condicao) 
    { 
        outro procedimento
    }
    else 
    { 
        mais um procedimento
    }
  • 1

    else if is different from elseif although both have the same practical result.

  • 1

    Thank you, I am beginner not yet have the knowledge of these nuância

5

In the elseif a condition is expected to execute a particular block of code while else is everything that did not satisfy the if condition. As for example the calculation of discount in a purchase where the customer wins 2% in purchases of value less than or equal to 100 and if it is greater 5%.

<?php
    $total = 300;
    if($total <= 100){
      $desconto = $total * 0.003;
    }else{
       $desconto = $total * 0.005;
    }

Now if you want to give different discount ranges it is necessary to use some elseif

<?php
    $total = 300;
    if($total <= 100){
      $desconto = $total * 0.003;
    }elseif($total > 150 && $total < 300){
       $desconto = $total * 0.005;
    }else{
        $desconto = $total * 0.007;
    }
  • Thank you for the reply!

5

elseif, is what the name suggests, a combination of if and Else. Like Else, it extends an if to perform different instructions in case the original if returns FALSE. However, unlike Else, it will execute an alternative expression only if the elseif condition returns TRUE. For example, the following code will display a is Bigger than b, a Equal to b or a is smaller than b:

<?php
if ($a > $b) {
    echo "a is bigger than b";
} elseif ($a == $b) {
    echo "a is equal to b";
} else {
    echo "a is smaller than b";
}
?>

There may be several elseifs within the same if. The first elseif expression (if any) that returns TRUE will be executed. In PHP, you can write 'Else if' (in two words) that the behavior will be identical to 'elseif' (in a single word). The syntactic meaning is a little different (if you are familiar with C, the behavior is the same) but at the bottom is that both will have exactly the same behavior.

elseif is only executed if the previous if or any elseif returns FALSE, and the current elseif returns TRUE.

Source: http://php.net/manual/en/control-structures.elseif.php

  • Thank you for the reply!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.