elseif/else if

(PHP 4, PHP 5, PHP 7, PHP 8)

elseif, como su nombre lo sugiere, es una combinación de if y else. Del mismo modo que else, extiende una sentencia if para ejecutar una sentencia diferente en caso que la expresión if original se evalúe como false. Sin embargo, a diferencia de else, esa expresión alternativa sólo se ejecutará si la expresión condicional del elseif se evalúa como true. Por ejemplo, el siguiente código debe mostrar a es mayor que b, a es igual que b o a es menor que b:

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

Puede haber varios elseif dentro de la misma sentencia if. La primera expresión elseif (si hay alguna) que se evalúe como true sería ejecutada. En PHP también se puede escribir 'else if' (en dos palabras) y el comportamiento sería idéntico al de 'elseif' (en una sola palabra). El significado sintáctico es ligeramente diferente (si se está familiarizado con C, este es el mismo comportamiento) pero la conclusión es que ambos resultarían tener exactamente el mismo comportamiento.

La sentencia elseif es ejecutada solamente si la expresión if precedente y cualquiera de las expresiones elseif precedentes son evaluadas como false, y la expresión elseif actual se evalúa como true.

Nota: Tenga en cuenta que elseif y else if serán considerados exactamente iguales sólamente cuando se utilizan llaves como en el ejemplo anterior. Al utilizar los dos puntos para definir las condiciones if/elseif, no debe separarse else if en dos palabras o PHP fallará con un error del interprete.

<?php

/* Método incorrecto: */
if ($a $b):
    echo 
$a." es mayor que ".$b;
else if (
$a == $b): // No compilará
    
echo "La línea anterior provoca un error del interprete.";
endif;


/* Método correcto: */
if ($a $b):
    echo 
$a." es mayor que ".$b;
elseif (
$a == $b): // Tenga en cuenta la combinación de las palabras.
    
echo $a." igual ".$b;
else:
    echo 
$a." no es ni mayor ni igual a ".$b;
endif;

?>

add a note add a note

User Contributed Notes 3 notes

up
6
Vladimir Kornea
17 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
-12
qualitycoder
9 years 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
-6
mparsa1372 at gmail dot com
3 years ago
The if...elseif...else statement executes different codes for more than two conditions.

Syntax:

if (condition) {
  code to be executed if this condition is true;
} elseif (condition) {
  code to be executed if first condition is false and this condition is true;
} else {
  code to be executed if all conditions are false;
}

Example:
Output "Have a good morning!" if the current time is less than 10, and "Have a good day!" if the current time is less than 20. Otherwise it will output "Have a good night!":

<?php
$t
= date("H");

if (
$t < "10") {
  echo
"Have a good morning!";
} elseif (
$t < "20") {
  echo
"Have a good day!";
} else {
  echo
"Have a good night!";
}
?>
To Top