If multiple conditions php. Conditions in PHP

Conditional operator allows you to skip or execute a certain block of code depending on the result of evaluating the specified expression - condition. We can say that the conditional statement is the decision point in the program, sometimes it is also called the branch 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 thought of as intersections where the program code forks 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 branch statements.

Syntax of the if statement:

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 (true), then the instruction is executed. If the expression evaluates to false, then the statement is not executed. An expression of any complexity can be used as a condition.

If only one statement is used in the body of the if statement, then it is possible, but not necessary, to enclose it in curly braces. However, if you want to execute more than one statement in the body of an if statement, then these several statements must be enclosed in curly braces. Note that the closing brace should not be followed by a semicolon.

Following code demonstrates the use of the if statement:

if statements can be nested within other if statements:

Pay attention to the last example: the instruction does not have to be written exactly under the if statement, if the instruction is not large in size, then it can be written on 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 of the if else statement is:

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

Modifying our previous example a bit, we can see how the if else statement works if the condition evaluates to false:

The if else statement can be nested. Such nested conditional statements are quite common in practice. An if statement is nested if it is nested within 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) , since it is not in the inner block, so the closest one to it is if($i) . The else statement inside the block is related to if($b) because that if is the closest to it.

elseif/else if construct

The if/else statement evaluates the value of the conditional expression and executes one or another fragment of the program code. But what if one of the many fragments needs to be executed? If you need to check several conditions in a row, then the elseif or else if construct is suitable for this (they are the same construct, just written differently). Formally, it is not independent. PHP construct is just a common style of programming that uses repeated if/else statements. It allows you to test additional conditions until a true one is found or an else block is reached. elseif/else if construct must be placed after the if statement and before the else statement, if any.

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

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

The lesson will cover conditional php statements: the if statement and the switch statement

Conditional statements in php 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 shorthand


Rice. 3.2. IF ELSE Conditional Syntax


Rice. 3.3. Full syntax conditional statement IF elseif

To summarize:

Full syntax:

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

  • The shortened syntax can do not contain part of the else construct and do not contain an additional elseif condition
  • Instead of the function word elseif, you can write else if (separately)
  • There can be several elseif in one if construct. The first elseif expression that evaluates to TRUE will be executed.
  • If there is an alternative elseif condition, 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 with the service word endif

Rice. 3.4. Conditional If and Endif statement in php

Example:

if($x > $y): echo $x." is greater than ".$y; elseif($x == $y): // cannot be written separately when using ":" else if echo $x." is equal to ".$y; else: echo $x." not > and not = ".$y; endif;

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

Logical operations in the condition

In an if condition, the following operations can be present in parentheses:

Example: check the value of a numeric variable: if it is less than or equal to 10, display a message "a number less than or equal to 10", otherwise display a message "a number 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 "and equals 4" if $a is indeed 4


1 Solution:
1 2 3 4

2 Solution:

1 2 3 A is 4

A is 4

php job 3_1: Output color translation from of English language 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 lie rule

In the if construct, in brackets should be boolean expression or a variable that is considered from the point of view of the algebra of logic, returning values ​​either true or false

Those. a single variable can act as a condition. Consider an example:

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

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

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

The LIE rule or what is considered false:

  • logical False
  • whole zero ( 0 )
  • real zero ( 0.0 )
  • empty line and the line «0»
  • array with no 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 statement echo $a; displays the value of the variable.

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

Logical constructions AND OR and NOT in the conditional operator

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

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

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

PHP switch statement

The switch statement or "switch" replaces several consecutive if constructs. In doing so, it compares one variable with multiple values. Thus, this is the most convenient means for organizing multibranching.

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 ​​(then they are specified in quotes) and numeric values ​​(without quotes).
  • The break statement in the construct is required. It exits the construct if the condition is true and the statement corresponding to the condition is executed. Without break, the statements of all cases will be executed, regardless of their truth.

Rice. 3.5. Conditional switch statement


Example: an array with full male 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 "Hi, Petya!" ; break ; case "Ivan" : echo "Hi, Vanya!" ; break ; case "Semyon" : echo "Hi, Vanya! " ; break ; default : echo "Hi, $names!"; break ; )

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

PHP job 3_4:

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

Add code:

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

Switch(...)( case 1: case 2: ... echo "It's a workday"; 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 sign? the condition is written, and on the right - two operators separated by a 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 ;
Nov 16 2016

By using conditional statements if, else, elseif, you can make a logical construct and write a script for anything. If we translate the names of these conditional statements, then we immediately understand what is at stake.

If translated as "if"

Else translates as "otherwise"

The logic of the construction of conditional statements is simple, we encounter such logic in life every day.

Well, for example, this statement:

If you turn on the light
That will be light.
Otherwise
It will be dark.

The words "if" and "otherwise" are just conditional statements.

It's the same in a programming language, but we set the conditions and events ourselves, using conditional statements, as the creators of our ideas.

if (condition is true) (
some action is taking place;
}
otherwise, if the condition is not true (
another action takes place;
}

The PHP syntax would look like this:

if (condition is true) (
Some action is being performed;
}
else(
Another action is taken if the condition is not true;
}
?>

Closer to practice.

We write a script for a button using conditional statements.

In folder open server-> domains create a folder and name it, for example, lesson3.local.

Create a file in the editor index.php(syntax set to PHP) and save it to a folder lesson3.local.

And write simple HTML button:




charset="utf-8">
<span>if-else construct</span>


action="" method="POST">



For attribute method in the tag form we set the value POST. This means that the form data will be submitted by the method POST. We will talk more about data transfer methods in the next lessons. What action Also, don't bother.

If we open index.php through openserver, then we will have just a button, but not yet working.

Now, let's write the script.

Let's say we want the phrase "You clicked the button" to appear when you click on a button.

Logically it would look like this:

If (button pressed)(
We display the phrase "You clicked on the button";
}

Let's approximate the expression to the PHP language using conditional operators:

if (button pressed) (
Phrase is displayed"You pressed the button";
}
?>

And now, under the HTML, we write the PHP code itself:

if (isset ($_POST[ "but" ]));
echo "You pressed the button";
}
?>

If this code is translated from PHP language into Russian, it will look like this:

If (set (form method POST [ buttons named 'but'])){
Phrase is displayed "You pressed the button";
}

And if it’s completely in Russian, then

If form data has been submitted POST method when you click on the button named but,
then the user will see the phrase "You clicked on the button."

This is how a programmer should think when writing a script.

Be careful, all quotes and brackets must be closed.

We write a script for two buttons.

The script will be like this:

If we press button1,
Then we see the message "You pressed button1".
Or, if we clicked on button2,
Then we will see the message "You clicked on button 2".




charset="utf-8">
<span>Script for two buttons</span>


action="" method="POST" >





if (isset ($_POST [ "but1" ]))(
echo "You pressed button 1";
}
elseif (isset ($_POST [ "but2" ]))(
echo "You pressed button 2";
}
?>

With the buttons, I think you figured it out. So you can write scripts for three buttons and for 10 ...

Write a greeting script by name.

The scenario is as follows: the user enters his name in the box, and when the button is clicked, a greeting phrase appears.

So, first we write the HTML form.




charset="utf-8">
<span>if-else construct</span>


action="" method="POST" >

Your name


type ="submit" name ="submit" value ="(!LANG:Submit" >!}




First we must create$ variable name, in it we will put the name that the user will enter.

$name=$_POST [ "name" ] ;

And then under HTML form we will write the construction already familiar to us, using conditional operator if:

$name=$_POST ["name" ];
if (isset ($_POST ["submit" ]))(
echo "Hi" ." " .$name ;
}
?>

We write the simplest authorization script.

Let's say we have only two users: Vasya and Petya. The system does not know other users.

If we enter the name Vasya,
then the phrase "Hello Vasya" will appear.
Or, if we enter the name Petya,
then the phrase "Hi Petya" will appear.
Otherwise, if we enter nothing, or enter a different name,
the phrase "Hi guest" will appear.




charset="utf-8">
<span>Simple authorization</span>


action="" method="POST" >

Your name


type ="submit" name ="submit" value ="(!LANG:Sign in" >!}





$name = $_POST["name"];
if ($name = = "Vasya" )(
echo "Hi" ." " .$name;
}
elseif ($name = = "Petya" )(
echo "Hi" ." " .$name ;
}
else(
echo "Hi guest" ;
}
?>

And finally, at the same time remember:

Greeting script depending on the time of day.

$hour = (int)strftime("%H" );
$welcome = " "; // Initialize variable for greeting
if ($hour > 0 && $hour<= 6 )
$welcome = "Good night!" ;
elseif ($hour > 6 && $hour<= 12 )
$welcome = "Good morning!" ;
elseif ($hour > 12 && $hour<= 18 )
$welcome = "Good afternoon!" ;
elseif ($hour > 18 && $hour<= 23 )
$welcome = "Good evening!" ;
else $welcome = "Good evening!" ;
$header = "$welcome Welcome to our site!";
?>



charset="utf-8">
<span>Time


<?php echo $header ?>



Thus, one can come up with many scenarios using conditional statements if, else, elseif. So, practice, I advise you to type the code by hand, and not copy it, so you will quickly master the PHP language.

This lesson is a little more difficult than the previous one, but don't be afraid, you should go to a higher level in PHP knowledge. In this article, we will focus on a construction that consists of several conditions. We continue to study the if-else condition operator for PHP.

Before we continue our study if-else statement, I highly recommend looking at the signs that are used in if conditions. Memorize them or write them down:

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

Not equal: !=
Example: if ($a != $b)

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

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

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

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

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

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

Now let's continue.

Double if-else condition

Where can it be applied? When I created an admin panel for one site, I used a double condition to check the login and password.
To create a double condition, you need to add two more variables, for example: $k = 55; $n = 88.
It will look like this:

if ($a != $b and $k != $n)

and - you already know that this means a logical "and".

How it will look in PHP code:

php basics for website

Explanation:
See, in the condition, we indicated that if the variables $a and $b are equal ($a == $b) and the variables $k and $n are not equal ($k != $n), the condition will be considered correct. And if the condition is correct, then this part of the code will work:

{
echo "Everything is OK :)";
}

Enter the address in the browser:

Result:

If the value of the variable $a is changed to the opposite value of the variable $b , then the condition will not be satisfied! Why? Yes, because the variables ($a == $b) are not equal to each other. If the condition is not met, another part of the code will work:

else
{
echo "Not all OK: (";
}

How it looks like in PHP code:

php basics for website

Save PHP code as "if-else.php" to "test-1" folder local server(see lesson 1).

Enter the address in the browser:

https://localhost/test-1/if-else.php

Result:

Nested if-else constructs.

What are nested if-else constructs? These are structures that consist of several conditions.

Now consider nested if-else constructs. Such constructs can consist of several conditions in the rules to be executed. For example, let's add two more variables $familiya 1 and $familiya 2 :

$ family 1 =" ivanov";
$ family 2 =" sidarov";

How it looks like in PHP code:

php basics for website Variables familiya1 and familiya2 contain different surnames."; ) else ( echo "It's not as bad as you think:(
Variables familiya1 and familiya2 contain the same surnames."; ) ) else ( echo "Not everything is OK:("; ) ?>

Explanation:
Look, here all the conditions have been met

If ($a == $b and $k != $n)

Variable $a is equal to variable $b and variable $k is not equal to $n . Here the conditions have been met, which means that this part of the code will work:

if ($familiya1 != $familiya2)
{
echo "Everything is OK :)
";
}

Since the $familiya variables 1 and $familiya 2 are not equal to each other and it's true,

$familiya1=" ivanov";
$familiya2=" sidarov";

then this part of the code will work:

{
echo "Everything is OK :)
The variables familiya1 and familiya2 contain different surnames.";
}

Let's see the result! Save the PHP code as "if-else.php" to the "test-1" folder of the local server (see lesson 1).

Enter the address in the browser:

https://localhost/test-1/if-else.php

Result:

If in variables $familiya1 and $familiya2 make the value the same:

$familiya1=" sidarov";
$familiya2=" sidarov";

then, alas, the conditions will not be fulfilled here, since the condition states that the variables must not be equal:

if ($family1 != $familiya2)

For this reason, this part of the code will work:

Else
{
echo " It's not as bad as you think :(

The variables familiya1 and familiya2 contain the same surnames.";
}

As a result, you will see a picture on the monitor:

Here we are completely finished topic " PHP if-else condition statement". To consolidate Lesson 5 and Lesson 6, I recommend that you work on creating your own conditions on your own.

And I'm going to prepare for you new lessons on the basics of PHP. Subscribe to blog updates if you don't want to miss PHP lessons.
Good luck!

Today you will learn PHP to make a conditions by using if-else statements.
With the help of conditions, you can do data validation, display messages under the condition you created, redirect the user to a secret page, etc.

There is nothing complicated in the if -else (if-else) construction, the main thing is to understand how to write the conditions correctly so that the script executes them. All this, a little, is similar to our life. For example:

You have to get up for work Monday through Friday at 6:30. What are you doing? You set an alarm. The condition, then, will be as follows: if today is Monday - Friday and the time is 6:30, the alarm rings, we get up and do certain actions (dress, drink coffee with a sandwich, brush our teeth, wash ourselves and go to work).

As you can see, a simple type of conditions is “if, then”, if Monday is 6:30, then we go to work.

PHP - if statement

Once again, we will consolidate what I said above and try to write code according to this scheme in the picture:

php basics for website "; ) echo "Respectfully, author of the blog Kostanevich S.V."; ?>

Save as "if.php" to the "test-1" folder of the local server (see).

Enter the address in the browser:

https://localhost/test-1/if.php

Result:

Explanation:

Please note that in the conditions we compared the $name variable with the value " site ". That is, they wrote in the condition that if the $name variable is equal to "site", by the way, the equal sign is indicated by a double equal sign (== ), then this condition is true, and if the condition is true, then the action is displayed. I wrote this code in actions:

echo "
";

I think it's sorted out here.

On a note:

== - equality. Example: if ($a == $b) .
!= is not an equality. Example: if ($a != $b) .
= - assign. Example: $a = 1 .

if-else condition statement

We figured out a simple condition, it was not difficult, but now let's complicate the task a little. Let's go back to our example:
From Monday to Friday at 6:30 you wake up and go to work as usual, but if today is Saturday or Sunday, then the alarm will not ring and you will perform other activities.

Now let's return to the PHP examples and try to write code according to this scheme:

php basics for website
"; ) echo "Respectfully, author of the blog Kostanevich S.V."; ?>

Save as "if-else.php" to the "test-1" folder of the local server (see lesson 1).

Enter the address in the browser:

https://localhost/test-1/if-else.php

Result:

As you can see, the variable $name and $n are equal. So the condition is true.

$name = "website";
$n = "site";
if ($name == $n )

Let's change the value and make the condition false, to do this, change the value in the variable, for example, like this:

$name = "site";
$n = "blog";
if ($name == $n )

you can do it like this:

$name = "site";
$n = "site";
if ($name != $n )

Now let's write the PHP code:

php basics for website "; ) else ( echo "action is false
"; ) echo "Respectfully, author of the blog Kostanevich S.V."; ?>

Result:

Explanation:

In the conditions, we compared the variable $name with the variable $n . When the variables had the same value, and the conditions had an equal sign (== ), the condition was true, this part of the code worked:

{
echo " Glad to see you on my blog $name!
";
}

As soon as we changed the value in the variables, the condition became false, and another part of the code started to work:

else
{
echo " action is false
";
}

Internet