Elseif else is an example of two lines. Conditional if statement in PHP. Abbreviated recording options

Conditional operator allows you to skip or execute a certain block of code, depending on the result of evaluating the specified expression - condition. A conditional statement can be said to be a decision point in a program, sometimes also called a branching statement. If we imagine that the program is a road, and the PHP interpreter is a traveler walking along it, then conditional statements can be represented as intersections, where the program code branches into two or more roads, and at such intersections the interpreter must choose which road to move on. ...

If statement

The if statement is the simplest of the branching statements.

The syntax for the if statement is:

The if statement first evaluates the conditional expression specified in parentheses, the result of this expression is a boolean value. If the result is true, then the statement is executed. If the expression returns false, then the statement is not executed. An expression of any complexity can be used as a condition.

If there is only one statement in the body of an if statement, then it is possible, but not required, to enclose it in curly braces. However, if you need to execute in the body of the if statement, not one statement, but several, then these several statements must be enclosed in curly braces. Note that you should not use a semicolon after the closing curly brace.

The following code demonstrates the use of the if statement:

If statements can be nested within other if statements:

conditional expression nested if statement if ($ j< 20) $a = $b; ?>

Pay attention to the last example: the statement does not have to be written exactly under the if statement, if the statement is not large in size, then it can be written in one line.

If else statement

And so we learned that the if statement allows you to execute statements if the condition is true. If the condition is false, then no action is taken. However, it is often necessary to execute some instructions if a certain condition is true, and other instructions if the condition is false. It is for such cases that if else branching is used. It consists of an if statement followed by a block of statements and keyword else followed by another block of statements.

The syntax for the if else statement is:

The else clause is optional. The block of statements located after else is executed by default, i.e. when the conditional expression in the if returns false. The else statement cannot be used apart from the if statement. The else block should be placed only after the if statement, it can be considered as the default action.

Modifying our previous example slightly, we can see how the if else statement works if the condition returns false:

The if else statement can be nested. Such nested conditionals are quite common in practice. An if statement is nested if it is located inside another if or else block. If the code uses several if statements in a row, then else always refers to the closest if:

The last else does not apply to if ($ a) as it is not in indoor unit so the closest to it is if ($ i). The else statement inside the block refers to if ($ b), because this if is the closest to it.

Elseif / else if

The if / else statement evaluates the value of the conditional expression and executes a particular piece of program code. But what if you need to execute one of many chunks? If you need to check several conditions in a row, then the elseif or else if construct is suitable for this (this is the same construct, just written differently). Formally, it is not a stand-alone PHP construct - it is just a common programming style that uses repeated if / else statements. It allows you to test additional conditions until a true one is found or the else block is reached. Elseif / else if must appear after the if statement and before the else statement, if any.

Three conditions are tested here, and different actions are taken depending on the value of the $ username variable.

In fact, there is nothing special about this snippet. It's just a sequence of if statements, where each if statement is part of the else statement of the previous if. For those who first encountered this form of notation and it is not very clear to him how it works, we will rewrite the same example, only in an equivalent syntactic form that fully shows the nesting of structures:

Some sources say that the select statement if else is independent operator... But it is not, if else is just a notation of the if selection statement. The if else statement allows the programmer to define an action when a condition is true and an alternative action when a condition is false. Whereas if allowed to define an action under a true condition.

The syntax for writing the select statement if else is:

If (/ * checked condition * /) (/ * body of the selection operator 1 * /;) else (/ * body of the selection operator 2 * /;)

It reads like this: “If the checked condition is true, then select statement body 1, otherwise (that is, the checked condition is false) is satisfied select statement body 2". Notice how the if else statement is written. The else word is deliberately shifted to the right to make the program code understandable and easy to read.

Let's look at the problem from the previous topic using if else. Let me remind you the condition of the problem: "You are given two numbers, you need to compare them."

// if_else.cpp: defines the entry point for the console application. #include "stdafx.h" #include using namespace std; int main (int argc, char * argv) (int a, b; cout<< "Vvedite pervoe chislo: "; cin >> a; cout<< "Vvedite vtoroe chislo: "; cin >> b; if (a> = b) // if a is greater than or equal to b, then (cout<< a << " >= " << b << endl; } else // иначе { cout << a << " <= " << b << endl; } system("pause"); return 0; }

In this code, we are interested inlines 14-20... These lines are read like this: if a (first number) greater than or equal b (second number), then execute the output statement inline 16

Cout<< a << " >= " << b << endl;

otherwise execute the output statement in line 19

Cout<< a << " <= " << b << endl;

In this ife, we use relation operations> = and<= . Условие перехода не совсем правильно, так как условие будет ложно только в том случае, если первое число будет меньше второго, во всех остальных случаях условие истинно. Значит, line 19 should be written like this

Cout<< a << " < " << b << endl; // в кавычках записать не меньше или равно, а просто меньше.

And this is how the program worked (see Figure 1).

Vvedite pervoe chislo: 15 Vvedite vtoroe chislo: -4 15> = -4 Press any key to continue. ... ...

Figure 1 - Operator of choice if else

Let me show you another example of using the if else selection statements (the so-called nested if else statements for multiple selection).

The task:
Create an algorithm that finds the value of y, if y = x, for x<0; у=0, при 0<=х<30; у=х 2 , при х>=30;

// inif_else.cpp: defines the entry point for the console application. #include "stdafx.h" #include using namespace std; int main (int argc, char * argv) (int x, y; cout<< "Vvedite x: "; cin >> x; if (x< 0) { y = x; // выполняется, если х меньше нуля } else { if ((x >= 0) && (x< 30)) { y = 0; // выполняется, если х больше либо равно нуля и меньше 30 } else { if (x >= 30) (y = x * x; // executed if x is greater than or equal to 30))) cout<< "y=" << y << endl; system("pause"); return 0; }

In this problem, three cases are possible:
1st case: x< 0 ;
2nd case: x lies in the range from 0 (including 0) to 30;
3rd case: x is greater than or equal to 30.

Notice the innovation !! V 17 line notation like this: if ((x> = 0) && (x< 30)) , i used symbols && - this. Boolean operation AND&& is needed to combine several simple conditions into one compound. In our case, it is necessary to check the truth of two conditions: the first - x> = 0, the second - x< 30 . Все проверяемое условие будет истинно, если истинны два простых условия. В математике правильной записью считается такая запись: 0 <= x < 30 , а в С++ правильной записью считается вот такая запись: (x >= 0) && (x< 30) или такая 0 <= x && x < 30 . Кстати круглые скобочки () && () не обязательны, так как условия простые, но для уверенности, я прописываю, всегда, данные скобочки и вам советую.

Analysis of a particular case:

Let's say the user entered the number 31. Starting from line 12, the conditions are checked. It reads like this: “If x (31 in our case)< 0, то выполнить оператор в line 14". But since 31> 0 the condition is false, we go to the word else (otherwise) line 15... Next, we check if the number 31 is included in the specified interval. It reads like this: if x> = 0 and x<30then execute the statement on line 19 ... But since the number 31 is not included in the specified interval, the condition is false. In detail line 17: the program will first check the first simple condition x> = 0 - it is true, and if the first is true, then the program will go on to check the second simple condition x< 30 – оно ложно. Следовательно всё составное условие ложно, ведь в составном условии у нас используется логическая операция && , а это значит, что все составное условие истинно только в том случае, когда истинны оба простых условия. Переходим к else (иначе), здесь у нас последний if , (line 22). Checking x> = 30 is performed. It reads like this: If x> = 30 then execute the operator on line 24 ... Finally, the condition is true, so the statement in line 24... AND line 28 prints the resulting value. Well, everyone, reviewed the program in the smallest detail. The result of the program, if the user entered the number 31 (see Figure 2)

12.09.2017

Not yet


Hello everyone!
Continuing to learn PHP basics from scratch!
In this tutorial, I will tell you about if else condition statement... Literally, if means "if" and else means "otherwise." The if else construction itself helps to verify the data and display the result (display messages, execute some command, redirect the user to a secret page or let them into the admin panel). To learn how to write the conditions correctly and understand the if else construction, I will give you a real life example that is very similar to the if else construction.
You give your brain a command: as soon as the alarm sounds (6:00), I have to get up, wash, brush my teeth, get dressed and gallop to work. If the alarm does not ring at 6:00, then you can sleep, since you do not need to run to work.
Did you notice the if else construct? The precondition will be the set alarm time "6:00". If the alarm clock rings, then we get up and run to work, if it doesn't ring (otherwise, they still say a lie), then we sleep on.
You can bring a lot of such examples from life, for example: if it rains, then I sit at home, if there is no rain, then I take the ball and go to play football.
So how can you write the if else construction? Very simple.
Let's go step by step and start with a simple condition - the if statement.

For a better understanding, I have drawn the diagram of the if statement in the form of a picture:

Now let's try to transform the life example I gave above into php code.

If you save the php file with this code and open it through the local server (see), the result will be:

⇒ Explanation of the code:
In the condition, I compared the variable $ weather with the value "rain" (line # 3). In human terms, this code sounds like this: if the variable $ weather is equal to the value "rain", then you need to display the text " I am sitting at home". By the way, let me remind you (if you forgot a little) that the equal sign is denoted by a double equal sign, like this (==). If you write another value to the $ weather variable (line number 2), for example, snow, then the browser will blank page because the conditions were not met.

→ PATTERN CODE "CONSTRUCTION if":

→ Cheat sheet:

Equality: ==
Example: if ($ a == $ b)

Not equality:! =
Example: if ($ a! = $ B)

More:>
Example: if ($ a> $ b)

Smaller:<
Example: if ($ a< $b)

Greater than or equal:> =
Example: if ($ a> = $ b)

Less than or equal to:<=
Example: if ($ a<= $b)

Logical "and": and
Example: if ($ a == $ b and $ c! = $ D)

Logical "or": or, ||
Example: if ($ a == $ b || $ c! = $ D)

Now we will try to display a message if the conditions have not been met, namely, if it is raining, I sit at home, if it is not raining, I take the ball and go to play football. For a better understanding, let's see the figure below:

Now we will translate the circuit into real code:

Result:

I take the ball and go to play football

⇒ Explanation of the code:
In the condition, I compared the $ weather variable with the value "rain" (line number 3), but since I assigned the value "sun" to the variable $ weather (line number 2), the condition was not met (the values ​​are not the same), which means that the second part of the code (else) will work:

Else (echo "I take the ball and go to play football"; // result if the condition is not true)

→ CODE-PATTERN "CONSTRUCTION if-else":

Double if-else condition

Moving on to a more complex one - double condition if-else.
Let's use an example to create a password and login check.

Target:
Create a condition for checking the login and password. If the password or login do not match, display an error message.

Let's get started.
First, let's create two variables $ logo and $ password with the corresponding values:

Please note that in the condition we separated the two variables with the "AND" operator. This means that two variables must be correct for the condition to be fulfilled, but since our condition does not match the password (sink # 4), it means that the condition is incorrect and you will see the following message on the screen:

Login or password is not correct

If you change the value of the $ password variable to "123" (line # 3), then the conditions will be fully met (line # 4):

Result:

welcome to admin panel

Nested if-else constructs

Nested construction- this is when there is another structure inside the structure. Explained not quite clearly? It doesn't matter, you will understand everything by example.

Target:
Create a condition for checking the login and password. If the password or login do not match, display an error message, if they match, then check the secret word, if the secret word does not match, display an error message, if it matches, then display the message " welcome to admin panel ".

Let's get started:

First, let's create three variables, $ logo, $ password and $ x with the corresponding values:

Now let's create a double condition to test the $ logo and $ password variables:

Now under the comment " // there will be one more condition with a secret word "(line number 7) write one more if-else construct with the condition of checking the variable $ x:

Since the secret word is incorrect (line number 8), the screen will display a message:

secret word is wrong

If you replace the value of the $ x variable with "BlogGOOD", then the secret word is also true:

Since the login and password are correct, and this means that the condition was met, the first part of the code worked, where it was necessary to check the secret word. Since the secret word is correct with the condition, then on the screen you will see the message:

welcome to admin panel

→ CODE-PATTERN "NESTED CONSTRUCTION if-else":

Elseif condition statement

Elseif construct is a combination of if and else statements that will help you check several conditions in a row.

Syntax:

Note, in lines # 6 and # 10, two words are specially written together "elseif", if you separate them with a space "else if", the code will generate an error.

Let's give a working code with a selection of programming tutorials.

Result:

You ordered the PHP tutorial

The elseif way can be written in the same way nested if else statement:

The result is the same, but it's easier to get confused (I got confused 2 times in my own code).

Addition to the lesson (you don't need to know yet):

There are several more options for how you can write the if else ( alternative syntax).
I will prepare a whole lesson about the alternative syntax, where I will explain and show everything. For now, just go over your eyes.
Code # 1:

Variable "$ a" contains value 15

Homework:
Try to substitute inequality (! =) Instead of equality (==) in the condition, or try with signs greater than less:

and also replace the "AND" operator with "OR".

Everyone, I'm waiting for you in the next lessons! Subscribe to blog updates!

Previous post
Next post

3.6K

In this article, we will show you how to use the PHP if… else… and elseif statements.

PHP conditional statements

PHP has several operators that you can use to make decisions:

  • If statement;
  • The if… else statement;
  • The if… elseif… statement. else;
  • The switch… case statement.

Below we will look at each of these operators.

If statement

If statement (like PHP elseif) is used to execute a block of code only if the specified condition is true. This is the simplest PHP conditional statement and can be written like this:

if (condition) (// Executable code)

Have a nice weekend!"If today is Friday:

Example:

If ... else statement

You can complicate the decision-making process by providing Alternative option... To do this, you need to add an else statement to the if. The if… else statement allows you to execute one block of code if the specified condition evaluates to true, and another block of code if false.

It can be written as follows:

if (condition) (// Code that will be executed if the condition is true) else (// Code that will be executed if the condition is false)

The code below outputs “ Have a nice weekend!"If today is Friday. Otherwise, “Have a nice day! ".

Example:

If… elseif… else statement

if… elseif… else statement ( not to be confused with PHP elseif else) is used to combine multiple if… else statements.

if (condition) (// Code that will be executed if the condition is true) elseif (condition) (// Code that will be executed if the condition is true) else (// Code that will be executed if the condition is false)

The code below outputs “ Have a nice weekend!"If today is Friday or" Have a nice Sunday! " if today is Sunday. Otherwise, “Have a nice day! ".

Example:

Ternary operator

The ternary operator provides a shorthand way to write PHP's if ... else and elseif statements. The ternary operator is denoted by the symbol question mark(?). It accepts three operands: a condition to test, a result for true, and a result for false.

To understand how this operator works, consider the following examples:

Example:

Using the ternary operator, the same code can be written more compactly:

Example:

The ternary operator in the example above selects the value to the left of the colon (that is, "Child") if the condition evaluates to true (that is, if $ age is less than 18) and the value to the right of the colon (ie, "Adult") if the condition evaluates to false.

Note. Code written using the ternary operator can be difficult to read. However, it provides a way to compact if-else and PHP elseif statements.

PHP7 null coalescing operator

PHP 7 introduced a new null coalescing operator (??) that can be used as a shorthand for the ternary operator when combined with the isset () function.

The lesson will consider conditional php statements: if statement and switch statement

Php conditional statements are represented by three main constructs:

  • condition operator if,
  • switch operator switch
  • and ternary operator.

Let's take a closer look at each of them.

PHP if statement

Fig 3.1. Conditional IF statement, shortened version


Rice. 3.2. IF ELSE conditional statement syntax


Rice. 3.3. Complete syntax for IF elseif conditional statement

Let's summarize:

The complete syntax is:

if (condition) (// if the condition is true operator1; operator2;) elseif (condition) (operator1; ...) else (// if the condition is false operator1; operator2;)

  • The shortened syntax can do not contain part of the construction with else and do not contain additional condition elseif
  • Instead of the function word elseif, you can write else if (separately)
  • There can be several elseifs in one if statement. The first encountered elseif expression equal to TRUE will be executed.
  • If there is an alternative condition elseif, the else clause must come last in the syntax.

A colon can be used in a conditional statement: instead of curly braces... In this case, the operator ends service word endif

Rice. 3.4. If and Endif conditional statement in php

Example:

if ($ x> $ y): echo $ x. "greater than". $ y; elseif ($ x == $ y): // when using ":" you cannot write separately else if echo $ x. "equals". $ y; else: echo $ x. "not> and not =". $ y; endif;

Important: When using a colon instead of curly braces elseif, you cannot write in two words!

Logical operations in a condition

The following operations can be present in the if clause in parentheses:

Example: check the value of a numeric variable: if it is less than or equal to 10, - issue a message "Number less than or equal to 10", in the opposite case, issue a message "Number is greater than 10"


Solution:

$ number = 15; if ($ number<=10) { echo "число меньше или равно 10"; } else { echo "число больше 10"; }

Blocks of php code can be broken, consider an example:

Example: Display html code "A is equal to 4" if the variable $ a is indeed 4


1 Solution:
1 2 3 4

2 Solution:

1 2 3 A equals 4

A equals 4

Php job 3_1: Display the translation of colors from English into Russian, checking the value of the variable (in which the color is assigned: $ a = "blue")


Php job 3_2: Find the maximum of three numbers

Comparison operations and the rule of lies

In the if statement, there must be a logical expression or a variable in parentheses that is considered from the point of view of logic algebra, returning values ​​either true or false

Those. a single variable can be used as a condition. Let's consider an example:

1 2 3 4 $ a = 1; if ($ a) (echo $ a;)

$ a = 1; if ($ a) (echo $ a;)

In the example, the translator php language will consider the variable in parentheses for the rule of lies:

The rule of LIE or what is considered to be false:

  • logical False
  • integer zero ( 0 )
  • valid zero ( 0.0 )
  • empty line and the line «0»
  • array without elements
  • object without variables
  • special type NULL

Thus, in the considered example, the variable $ a is equal to one, respectively, the condition will be true and the operator echo $ a; will display the value of the variable.

Php job 3_3: given a variable a with a string value. If a is equal to the name, then output "Hello name!" if a is equal to empty value then output "Hi stranger!"

Logical constructs AND OR and NOT in a conditional operator

  1. Sometimes it is necessary to provide for the fulfillment of several conditions at the same time. Then the conditions combine logical operator AND — && :
  2. $ a = 1; if ($ a> 0 || $ a> 1) (echo "a> 0 or a> 1";)

  3. To indicate that the condition is false, use logical operator NOT — ! :
  4. 1 2 3 4 $ a = 1; if (! ($ a< 0 ) ) { echo "a не < 0" ; }

    $ a = 1; if (! ($ a<0)) { echo "a не < 0"; }

Switch PHP statement

The switch statement or "switch" replaces several consecutive if statements. In doing so, it compares one variable with a set of values. Thus, it is the most convenient remedy. for organizing multi-branching.

Syntax:

1 2 3 4 5 6 7 8 9 10 switch ($ variable) (case "value1": statement1; break; case "value2": statement2; break; case "value3": statement3; break; [default: statement4; break;])

switch ($ variable) (case "value1": statement1; break; case "value2": statement2; break; case "value3": statement3; break;)

  • The operator can check both string values ​​(in which case they are indicated in quotes) and numeric (without quotes).
  • The break statement in the construction is required. It exits the construction if the condition is true and the statement corresponding to the condition is executed. Without break, all case statements will be executed regardless of their truth.

Rice. 3.5. Conditional Switch statement


Example: an array with full masculine names is given. Check the first element of the array and, depending on the name, issue a greeting with a short name.


Solution:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 $ names = array ("Ivan", "Peter", "Semyon"); switch ($ names [0]) (case "Peter": echo "Hello, Petya!"; break; case "Ivan": echo "Hello, Vanya!"; break; case "Semyon": echo "Hello, Vanya! "; break; default: echo" Hello, $ names! "; break; )

$ names = array ("Ivan", "Peter", "Semyon"); switch ($ names) (case "Peter": echo "Hello, Petya!"; break; case "Ivan": echo "Hello, Vanya!"; break; case "Semyon": echo "Hello, Vanya!"; break ; default: echo "Hello, $ names!"; break;)

Php job 3_4:

  • Create a variable $ day and assign it an arbitrary numeric value
  • Use the switch statement to output the phrase "This is a working day" if the value of the variable $ day falls within the range of numbers from 1 to 5 (inclusive)
  • Output the phrase "It's a day off" if the value of the variable $ day is 6 or 7
  • Output the phrase "Unknown day" if the value of the $ day variable is not in the range of numbers from 1 to 7 (inclusive)

Complete the code:

1 2 3 4 5 6 7 8 9 10 11 12 ... switch (...) (case 1: case 2: ... echo "This is a working day"; break; case 6: ... default: ...)

Switch (...) (case 1: case 2: ... echo "This is a working day"; break; case 6: ... default: ...)

PHP ternary operator

Ternary operator, i.e. with three operands, has a fairly simple syntax, in which to the left of the? the condition is written, and on the right - two operators separated by the sign:, to the left of the sign the operator is executed if the condition is true, and to the right of the sign: the operator is executed if the condition is false.

condition? operator1: operator2;