What is the difference between elseif and elseif?

20

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

    
asked by GWER 10.04.2015 в 14:44
source

6 answers

20

The else has no condition to check and is used at the end / after a series of if / elseif , as "general case".

The elseif , like if , is used in cases where it is necessary to check the authenticity of a condition. So instead of multiple if , we use n elseif , and at the end the general case within 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 is hoje only the first condition is verified and the other lines will not be run.

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

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

Notes:

elseif is very useful for avoiding long scans since conditions are excluded (if one% of the others are not even tested / run).

In many conditions, it may be best to use true as @Zuul mentioned . However, this switch / if / elseif structure allows different checks on each condition, whereas else checks only one variable that can have different values.

Example that switch can not play:

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 }
    
answered by 10.04.2015 / 14:46
source
16

We can read in the documentation that:

  

elseif , as its name suggests, is a combination of if and else . As else , it extends a if command to execute a different statement if the condition of the if original evaluates to FALSE .

     

However, unlike else , it will execute that alternative expression only if the conditional expression of elseif evaluates to TRUE .

In short, elseif introduces new conditions into 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 default value.

Note that when checks are many, if~elseif~else turns out to be inefficient, making it preferable to use a control structure switch() .

See this related question that talks about using switch instead of multiple elseif although it refers to JavaScript, it applies to PHP in terms of performance.


Conventions

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

View on 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";
    }
    
  • Output:

    a é igual a b  
    a é maior que b
    
  

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


Warnings

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

View on 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++;
    }
    
  • Output:

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

Just an 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 leads us to application performance:

// 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 perform all the conditions, even if you do not need them, and it is here that else if helps to deal with the issue, because after a condition evaluated for true, the rest are ignored thus avoiding consumption unnecessary resources!

    
answered by 10.04.2015 в 15:01
8

Everyone has already explained well what it is. I'll try to show it another way.

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

See 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 a if will be executed. The block of if works under a regime of short-circuit , that is , when one of its sub-blocks is executed, the others are no longer executed. They are excluding. Then the result of it will be according to the first block that the condition results in true . In the second example, they can all run if each of them individually results in true . It might even be your intention, but it does not seem to be. In this case if the value is less than 10, it will execute 3 times and will generate a cumulative value that you probably should not do.

Notice that the opposite is also true. If you need all ifs to be evaluated regardless of the outcome of the previous ones, obviously they need to be independent, they can not constitute 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 ifs is independent.

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

Of course you can only use if and else and get the same result, but look how weird it is:

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

The form using elseif can be seen as syntax sugar for the form with else with ifs nested. And it's important to keep your code healthy, especially if you have too many sub-blocks to execute.

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

Obviously it does not make sense to have more than a 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 it will not even be evaluated.

If you already understand switch you can see elseif in a similar way. Of course, elseif allows more powerful conditions, case allows only equality comparison of a single value. The elseif is short-circuit , case is not, if you do not put a break , it will try to evaluate the others. But the buildings are similar. You use both if the comparisons are related. It does not make sense, even if it works, to put unrelated comparisons in the same block.

    
answered by 10.04.2015 в 15:32
4

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 else if else simplification:

if (condicao) 
    { 
         procedimento
    }
    else if (outra condicao) 
    { 
        outro procedimento
    }
    else 
    { 
        mais um procedimento
    }
    
answered by 10.04.2015 в 15:03
4

No elseif is expected to be a condition for executing a particular block of code while else is all that does not satisfy the if condition. As for example the calculation of discount on a purchase where the customer earns 2% on 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;
    }
    
answered by 10.04.2015 в 14:47
3

elseif, is what the name suggests, a combination of if and else. Like the else, it extends an if to execute different statements in case the original if return FALSE. However, other than 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 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 execute. 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 bit different (if you are familiar with C, the behavior is the same) but deep down it is that both will have exactly the same behavior.

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

Source: link

    
answered by 10.04.2015 в 14:50