Php alternative syntax if

Альтернативный синтаксис управляющих структур

PHP предлагает альтернативный синтаксис для некоторых его управляющих структур, а именно: if, while, for, foreach и switch. В каждом случае основной формой альтернативного синтаксиса является изменение открывающей фигурной скобки на двоеточие (:), а закрывающей скобки на endif;, endwhile;, endfor;, endforeach; или endswitch; соответственно.

В приведенном выше примере, блок HTML «A равно 5» вложен внутрь структуры if написанной с альтернативным синтаксисом. HTML блок будет показан только если переменная $a равна 5.

Альтернативный синтаксис также применяется и к else и elseif. Ниже приведена структура if с elseif и else в альтернативном формате:

if ( $a == 5 ):
echo «a равно 5» ;
echo «. » ;
elseif ( $a == 6 ):
echo «a равно 6» ;
echo «. » ;
else:
echo «a не равно ни 5 ни 6» ;
endif;
?>

Замечание:

Смешивание синтаксиса в одном и том же блоке управления не поддерживается.

Любой вывод (включая пробельные символы) между выражением switch и первым case приведут к синтаксической ошибке. Например этот код не будет работать:

В то же время следующий пример будет работать, так как завершающий перевод строки после выражения switch считается частью закрывающего ?> и следовательно ничего не выводится между switch и case:

Источник

Php alternative syntax if

elseif , as its name suggests, is a combination of if and else . Like else , it extends an if statement to execute a different statement in case the original if expression evaluates to false . However, unlike else , it will execute that alternative expression only if the elseif conditional expression evaluates to true . For example, the following code would display a is bigger than b , a equal to b or a is smaller than b :

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» ;
>
?>

There may be several elseif s within the same if statement. The first elseif expression (if any) that evaluates to true would be executed. In PHP, it’s possible to write else if (in two words) and the behavior would be identical to the one of elseif (in a single word). The syntactic meaning is slightly different (the same behavior as C) but the bottom line is that both would result in exactly the same behavior.

The elseif statement is only executed if the preceding if expression and any preceding elseif expressions evaluated to false , and the current elseif expression evaluated to true .

Note: Note that elseif and else if will only be considered exactly the same when using curly brackets as in the above example. When using a colon to define if / elseif conditions, the use of elseif in a single word becomes necessary. PHP will fail with a parse error if else if is split into two words.

/* 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;

Читайте также:  Java listeners and adapters

/* 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;

Источник

Conditional Control Flow in PHP Tutorial (with if, else..if, else, switch, match & the ternary operator)

In this tutorial we learn how to control the flow of our PHP application through conditional logic with if, else if, else and switch statements.

We also cover the alternative syntax for if and switch statements (often used in applications like WordPress) and the ternary operator for simple if/else statements.

Finally, we cover the new match expression that was introduced in PHP 8.

What is conditional control flow

PHP allow us to control the flow of our application by evaluating conditional expressions and executing sections of code based on the result.

As an example, let’s consider an application that allows a userbase. After registering, the user may log into their personal administration area and perform certain tasks.

The login process would be handled by the following (simplified) logic:

  1. Check the user’s email address and password against the database.
  2. If the user’s email and password is correct, let them through to the member area. If not, ask the user to retry.

Step 2 is our conditional logic. In code it would look something like the following.

if username AND password == correct execute code for login execute code to redirect to member area otherwise ask the user to try again

So, specific sections of code gets executed based on the outcome of the conditions.

How to use an if statement

An if statement consists of at least 3 tokens.

  • The if keyword.
  • A condition block for our condition, wrapped in () (parentheses)
  • An execution block for the logic we want to execute if the condition proves true, wrapped in <> (curly braces)
 The statement reads as follows:

if (condition is true), execute < code >.

In the example above we evaulate if 1 + 1 equals 2. It does of course and so the interpreter will have permission to go into the code block between the curly braces and execute the echo statement.

How to use an else..if ladder

The else..if statement is an optional condition that allows us to evaluate more conditions when the if condition evaluates to false.

We simply write another if statement below our first one and seperate the two with the else keyword.

  When the if statement’s condition proves false, the interpreter will evaluate the else if condition.
Because the if condition is false, the interpreter will move on to the next one in the group and evaluate its condition. If the condition proves true, like it does in the example, it will execute that statement’s execution block.

We are allowed to create as many else if statements as we need. That’s why it’s called a ladder.

The interpreter will go down the ladder and execute any statement’s execution block if their condition proves true.

How to use an else fallback statement

The optional else statement works as a catch-all for anything that an if and/or else if doesn’t catch. Think of it as a last resort situation.

The else statement has no conditional expression, but does allow an execution code block.

Источник

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.

Источник

Оцените статью