Php else if without else

PHP if elseif

Summary: in this tutorial, you’ll learn about the PHP if elseif statement to execute code blocks based on multiple boolean expressions.

Introduction to the PHP if elseif statement

The if statement evaluates an expression and executes a code block if the expression is true:

 if (expression) Code language: HTML, XML (xml)

The if statement can have one or more optional elseif clauses. The elseif is a combination of if and else :

 if (expression1) < statement; >elseif (expression2) < statement; >elseif (expression3) Code language: HTML, XML (xml)

PHP evaluates the expression1 and execute the code block in the if clause if the expression1 is true .

If the expression1 is false , the PHP evaluates the expression2 in the next elseif clause. If the result is true , then PHP executes the statement in that elseif block. Otherwise, PHP evaluates the expression3 .

If the expression3 is true , PHP executes the block that follows the elseif clause. Otherwise, PHP ignores it.

Notice that when an if statement has multiple elseif clauses, the elseif will execute only if the expression in the preceding if or elseif clause evaluates to false .

The following flowchart illustrates how the if elseif statement works:

The following example uses the if elseif statement to display whether the variable $x is greater than $y :

 $x = 10; $y = 20; if ($x > $y) < $message = 'x is greater than y'; > elseif ($x < $y) < $message = 'x is less than y'; > else < $message = 'x is equal to y'; > echo $message;Code language: HTML, XML (xml)

The script shows the message x is less than y as expected.

PHP if elseif alternative syntax

PHP also supports an alternative syntax for the elseif without using curly braces like the following:

 if (expression): statement; elseif (expression2): statement; elseif (expression3): statement; endif;Code language: HTML, XML (xml)
  • Use a semicolon (:) after each condition following the if or elseif keyword.
  • Use the endif keyword instead of a curly brace ( > ) at the end of the if statement.

The following example uses the elseif alternative syntax:

 $x = 10; $y = 20; if ($x > $y) : $message = 'x is greater than y'; elseif ($x < $y): $message = 'x is less than y'; else: $message = 'x is equal to y'; endif; echo $message; Code language: HTML, XML (xml)

The alternative syntax is suitable for use with HTML.

PHP elseif vs. else if

PHP allows you to write else if (in two words) that has the same result as elseif (in a single word):

 if (expression) < statement; >else if (expression2) Code language: PHP (php)

The else if in this case, is the same as the following nested if. else structure:

if (expression) < statement; >else < if (expression2) < statement2; >>Code language: JavaScript (javascript)

If you use the alternative syntax, you need to use the if. elseif statement instead of the if. else if statement. Otherwise, you’ll get an error.

The following example doesn’t work and cause an error:

 $x = 10; $y = 20; if ($x > $y) : echo 'x is greater than y'; else if ($x < $y): echo 'x is equal to y'; else: echo 'x is less than y'; endif;Code language: HTML, XML (xml)

Summary

  • Use the if. elseif statement to evaluate multiple expressions and execute code blocks conditionally.
  • Only the if. elseif supports alternative syntax, the if. else if doesn’t.
  • Do use the elseif whenever possible to make your code more consistent.

Источник

elseif/else if

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

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.

/* Некорректный способ: */
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;

Источник

PHP if. else. elseif Statements

Conditional statements are used to perform different actions based on different conditions.

PHP Conditional Statements

Very often when you write code, you want to perform different actions for different conditions. You can use conditional statements in your code to do this.

In PHP we have the following conditional statements:

  • if statement — executes some code if one condition is true
  • if. else statement — executes some code if a condition is true and another code if that condition is false
  • if. elseif. else statement — executes different codes for more than two conditions
  • switch statement — selects one of many blocks of code to be executed

PHP — The if Statement

The if statement executes some code if one condition is true.

Syntax

Example

Output «Have a good day!» if the current time (HOUR) is less than 20:

PHP — The if. else Statement

The if. else statement executes some code if a condition is true and another code if that condition is false.

Syntax

if (condition) code to be executed if condition is true;
> else code to be executed if condition is false;
>

Example

Output «Have a good day!» if the current time is less than 20, and «Have a good night!» otherwise:

if ($t < "20") echo "Have a good day!";
> else echo «Have a good night!»;
>
?>

PHP — The if. elseif. else Statement

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!»:

if ($t < "10") echo "Have a good morning!";
> elseif ($t < "20") echo "Have a good day!";
> else echo «Have a good night!»;
>
?>

PHP — The switch Statement

The switch statement will be explained in the next chapter.

Источник

Читайте также:  Docker compose php apache mysql
Оцените статью