elseif/else if

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

Конструкция elseif, как её имя и говорит есть сочетание if и else. Аналогично else, она расширяет оператор if для выполнения различных выражений в случае, когда условие начального оператора if эквивалентно false. Однако, в отличие от else, выполнение альтернативного выражения произойдёт только тогда, когда условие оператора elseif будет являться равным true. К примеру, следующий код может выводить a больше, чем b, a равно b или a меньше, чем b:

<?php
if ($a $b) {
    echo 
"a больше, чем b";
} elseif (
$a == $b) {
    echo 
"a равен b";
} else {
    echo 
"a меньше, чем b";
}
?>

Может быть несколько elseif в одном выражении if. Первое выражение elseif (если оно есть) равное true будет выполнено. В PHP вы также можете написать 'else if' (в два слова), и тогда поведение будет идентичным 'elseif' (в одно слово). Синтаксически значение немного отличается (если вы знакомы с языком С, это то же самое поведение), но в конечном итоге оба выражения приведут к одному и тому же результату.

Выражение elseif выполнится, если предшествующее выражение if и предшествующие выражения elseif эквивалентны false, а текущий elseif равен true.

Замечание: Заметьте, что elseif и else if будут равнозначны только при использовании фигурных скобок, как в примерах выше. Если используются синтаксис с двоеточием для определения условий if/elseif, вы не должны разделять else if на два слова, иначе это вызовет фатальную ошибку в PHP.

<?php

/* Некорректный способ: */
if($a $b):
    echo 
$a." больше, чем ".$b;
else if(
$a == $b): // Не скомпилируется.
    
echo "Строка выше вызывает фатальную ошибку.";
endif;


/* Корректный способ: */
if($a $b):
    echo 
$a." больше, чем ".$b;
elseif(
$a == $b): // Заметьте, тут одно слово.
    
echo $a." равно ".$b;
else:
    echo 
$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