PHP
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

Sintaxe alternativa para estruturas de controle> <else
Last updated: Fri, 22 Aug 2008

view this page in

elseif/else if

elseif, como seu nome sugere, é uma combinação de if e else. Da mesma forma que o else, ele estende um comando if para executar uma instrução diferente no caso de a expressão if original ser avaliada como FALSE. Porém, ao contrário de else, ele executará aquela expressão alternativa somente se a expressão condicional do elseif for avaliada como TRUE. Por exemplo, o código a seguir mostraria a é maior que b, a é igual a b ou a é menor que b:

<?php
if ($a $b) {
    echo 
"a é maior que b";
} elseif (
$a == $b) {
    echo 
"a é igual a b";
} else {
    echo 
"a é menor que b b";
}
?>

Podem haver vários elseifs dentro da mesma instrução if. A primeira expressão elseif (se houver) que for avaliada como TRUE será executada. No PHP, você também pode escrever 'else if' (em duas palavras) e o comportamento será idêntico a um 'elseif' (em uma só palavra). O significado sintático é ligeiramente diferente (se você está familiarizado com C, eles tem o mesmo comportamento), mas no final das contas ambos teriam exatamente o mesmo comportamento.

O comando elseif só é executado se a expressão if precedente e quaisquer expressões elseif anteriores forem avaliadas como FALSE, e a expressão elseif atual for avaliada como TRUE.

Nota: Note que elseif e else if somente será considerado exatamente o mesmo quando usando chaves com no exemplo acima. Quando usando dois pontos para definir sua condição if/elseif, você não deve separar else if em duas palavras, ou o PHP falhará com um parse error.

<?php

/* Método incorreto: */
if($a $b):
    echo 
$a." is greater than ".$b;
else if(
$a == $b): // Não compilará.
    
echo "The above line causes a parse error.";
endif;


/* Método correto: */
if($a $b):
    echo 
$a." is greater than ".$b;
elseif(
$a == $b): // Note a combinação das palavras.
    
echo $a." equals ".$b;
else:
    echo 
$a." is neither greater than or equal to ".$b;
endif;

?>



add a note add a note User Contributed Notes
elseif/else if
31-Jan-2007 11:54
There is no good way to interpret the dangling else.  One must pick a way and apply rules based on that. 

Since there is no endif before an else, there is no easy way for PHP to know what you mean.
Vladimir Kornea
27-Dec-2006 06:59
The parser doesn't handle mixing alternative if syntaxes as reasonably as possible.

The following is illegal (as it should be):

<?
if($a):
    echo $a;
else {
    echo $c;
}
?>

This is also illegal (as it should be):

<?
if($a) {
    echo $a;
}
else:
    echo $c;
endif;
?>

But since the two alternative if syntaxes are not interchangeable, it's reasonable to expect that the parser wouldn't try matching else statements using one style to if statement using the alternative style. In other words, one would expect that this would work:

<?
if($a):
    echo $a;
    if($b) {
      echo $b;
    }
else:
    echo $c;
endif;
?>

Instead of concluding that the else statement was intended to match the if($b) statement (and erroring out), the parser could match the else statement to the if($a) statement, which shares its syntax.

While it's understandable that the PHP developers don't consider this a bug, or don't consider it a bug worth their time, jsimlo was right to point out that mixing alternative if syntaxes might lead to unexpected results.

Sintaxe alternativa para estruturas de controle> <else
Last updated: Fri, 22 Aug 2008
 
 
show source | credits | stats | sitemap | contact | advertising | mirror sites