elseif/else if

(PHP 4, PHP 5)

elseif, é o que o nome sugere, uma combinação do if e do else. Como o else, ele extende um if para executar instruções diferentes no caso do if original retornar FALSE. Entretanto, diferente do else, ele executará uma expressão alternativa somente se a condição do elseif retornar TRUE. Por exemplo, o código a seguir exibirá a is bigger than b, a equal to b ou 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";
}
?>

Pode haver vários elseifs dentro do mesmo if. A primeira expressão elseif (se houver) que retornar TRUE será executado. No PHP, você pode escrever 'else if' (em duas palavras) que o comportamento será idêntico a 'elseif' (em uma única palavra). O significado sintático é um pouco diferente (se você está familiarizado com C, o comportamento é o mesmo) mas no fundo é que ambos terão exatamente o mesmo comportamento.

O elseif só é executado se o if precedente ou qualquer elseif retornar FALSE, e o elseif atual retornar TRUE.

Nota: Note que elseif e else if só serão considerados exatamente iguais se usados com chaves como no exemplo abaixo. Quando usando com dois pontos (:) para definir as condições if/elseif, você não pode separar else if em duas palavras, ou o PHP irá falhar com um erro de interpretação.

<?php

/* Incorrect Method: */
if($a $b):
    echo 
$a." is greater than ".$b;
else if(
$a == $b): // Will not compile.
    
echo "The above line causes a parse error.";
endif;


/* Correct Method: */
if($a $b):
    echo 
$a." is greater than ".$b;
elseif(
$a == $b): // Note the combination of the words.
    
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 7 notes

up
32
Vladimir Kornea
8 years ago
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.
up
5
qualitycoder
5 months ago
The reason 'else if' (with a space) works with traditional syntax and not colon syntax is because of a technicality.

<?php
 
if($var == 'Whatever') {

  } else if(
$var == 'Something Else') {

  }
?>

In this instance, the 'else if' is a shorthand/inline else statement (no curly braces) with the if statement as a body. It is the same things as:

<?php
 
if($var == 'Whatever') {

  } else {
      if(
$var == 'Something Else') {

      }
  }
?>

If you were to write this with colon syntax, it would be:

<?php
 
if($var == 'Whatever'):

  else:
      if(
$var == 'Something Else'):

      endif;
  endif;
?>
up
-18
peter dot mlich at volny dot cz
11 months ago
To  Rudi / 3 years ago

Try switch in switch($name) case 'word': break; . --- slow
Try if/else and  if/elseif in $name='word'. --- in my fast test, place 3
Try isset in isset($array[$name]). ---  place 1
Try in_array in in_array($name,$array). --- slow
Try array_key_exists in array_key_exists($name,$array).

Try return (end function) in if/elseif with  -- place 2
if('word'==$name) {
  $parsed[$name]=$text;
  return;
  } 
elseif('word'==$name) {
  $parsed[$name]=$text;
  return;


PHP 5.35, xml_parse function, i parsed 9.2MB xml file to sql, script in place 1 do it at 11.54s (do more than only condition)
up
-33
Anonymous
8 years ago
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.
up
-35
Anonymous
1 year ago
In addition to what Rudi  wrote,
I ran his test script  on Debian 6 with php 5.3.26 where his findings are true, elseif is faster than else if.
Then I ran his script on Windows 7 with php 5.4.7, where results are the opposite, else if is faster than elseif.
up
-61
Anonymous
1 year ago
The word 'elseif' is a not a combination of "if and else," but a combination of "else and if."
up
-81
Rudi
4 years ago
Note that } elseif() { is somewhat faster than } else if() {

===================================
Test (100,000,000 runs):
<?php
$start
= microtime(true);
for(
$i = 0; $i < 100000000; $i++) {
    if(
2 === 0) {} else if(2 === 1) {} else {}
}
$end = microtime(true);
echo
"1: ".($end - $start)."\n";
unset(
$start, $end);

$start = microtime(true);
for(
$i = 0; $i < 100000000; $i++) {
    if(
2 === 0) {} elseif(2 === 1) {} else {}
}
$end = microtime(true);
echo
"2: ".($end - $start);
?>

===================================
Result (depending on hardware configuration):
1: 20.026723146439
2: 20.20437502861
To Top