Php if else examples. Basics of IF-ELSE construction in PHP. Nested if-else constructs

Nov 16 2016

By using conditional statements if, else, elseif you can create a logical construct and write a script for anything. If we translate the names of these conditional statements, then we’ll immediately understand what we’re talking about.

If translated as "if"

Else translated as "otherwise"

The logic behind the construction of conditional statements is simple; we encounter this kind of logic in life every day.

Well, for example, this statement:

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

The words “if” and “else” are just conditional statements.

In a programming language it’s the same, but we set the conditions and events ourselves, using conditional statements, as the creators of our ideas.

if (condition is true) (
some action takes place;
}
else if the condition is not true (
another action occurs;
}

The PHP syntax would look like this:

if (condition is true) (
Some action is performed;
}
else(
Performs another action if the condition is not true;
}
?>

Closer to practice.

We write a script for a button using conditional statements.

In folder Open Server -> domains Let's create a folder and name it, for example, lesson3.local.

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

And let's write a 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 sent using the method POST. We will talk more about data transfer methods in the following lessons. What's happened action Don't worry too much just yet.

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

Well, now we write the script itself.

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 pressed the button”;
}

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

if (button pressed) (
The phrase is displayed“You pressed the button”;
}
?>

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

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

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

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

And if completely in Russian, then

If the form data was submitted using the POST method when a button named but was clicked,
then the user will see the phrase “You clicked the button.”

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

Be careful that all quotes and parentheses must be closed.

We are writing 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 pressed button 2,
Then we will see the message “You pressed button 2.”




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


action="" method="POST" >







if (isset ($_POST [ "but1" ]))(
echo "You pressed button1";
}
elseif(isset($_POST["but2"]))(
echo "You pressed button2";
}
?>

I think you've figured out the buttons. So you can write scripts for three buttons and for 10...

We write a greeting script by name.

The scenario is this: the user enters his name in the window, and when he clicks the button, 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 ="Submit" >!}






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

$name=$_POST [ "name" ] ;

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

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

We are writing a simple 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 “Hello Petya” will appear.
Otherwise, if we enter nothing, or enter a different name,
then the phrase “Hello guest” will appear.




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


action="" method="POST" >

your name


type ="submit" name ="submit" value ="Login" >!}







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

And finally, remember at the same time:

Greeting script depending on the time of day.

$hour = (int)strftime ("%H" );
$welcome = " "; // Initialize the greeting variable
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 ?>





So you can come up with many scenarios using conditional statements if, else, elseif. So, practice, I advise you to type the code by hand rather than copy it, this way you will quickly master the PHP language.

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

if statement

The if statement is the simplest of the branch statements.

The syntax of the if statement is:

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

If the body of the if statement uses only one instruction, then enclosing it in curly braces is possible, but not necessary. However, if you need to execute more than one instruction in the body of an if statement, then these several instructions must be enclosed in curly braces. Please note that there should not be 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:

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 in one line.

if else statement

And so we learned that the if statement allows you to execute instructions if the condition is true. If the condition is false, then no action is performed. However, it is often necessary to execute certain 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 an else keyword followed by another block of statements.

The syntax of the if else statement is:

The else statement is optional. The block of instructions located after else is executed by default, i.e. when the conditional expression in if returns false . The else statement cannot be used separately from the if statement. The else block should only appear after the if statement; it can be considered 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 conditional statements occur quite often in practice. An if statement is nested if it is nested inside another if or else block. If your code uses multiple if statements in a row, the else always refers to the closest if:

The last else does not apply to if($a) because 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 this if is the closest one to it.

elseif/else if construct

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

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

There's really nothing special about this piece. It is simply a sequence of if statements, where each if statement is part of the else clause of the previous if statement. For those who have encountered this form of notation for the first time and do not really understand how it works, we will rewrite the same example, only in an equivalent syntactic form that fully shows the nesting of structures:

This lesson is a little more complicated than the previous one, but don't be afraid, you should move up to a higher level in your knowledge of PHP. This article will focus on a design that consists of several conditions. We continue to study the if-else conditional operator for PHP.

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

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

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

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

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

Greater than or equal to: >=
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 logical “and”.

How it will look in PHP code:

basics of php for a website

Explanation:
Look, 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 your 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 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 everything is OK: (";
}

How it looks in PHP code:

basics of php for a website

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

Enter the address in your browser:

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

Result:

Nested if-else constructs.

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

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

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

How it looks in PHP code:

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

Explanation:
Look, all the conditions have been met here

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

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

if ($family1 != $family2)
{
echo "Everything is OK :)
";
}

Since $family variables 1 and $family 2 they are not equal to each other and this is true,

$family1=" ivanov";
$family2=" sidarov";

then this part of the code will work:

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

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

Enter the address in your browser:

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

Result:

If the variables $familiya1 and $familiya2 are set to the same value:

$family1=" sidarov";
$family2=" sidarov";

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

if ($family1 != $family2)

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 last names.";
}

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

So we have completely finished the topic “ If-else conditional statement for PHP" To reinforce Lesson 5 and Lesson 6, I recommend working on creating your own conditions yourself.

And I’ll go prepare new lessons on PHP basics for you. Subscribe to blog updates if you don't want to miss PHP lessons.
Best wishes!

(PHP 4, PHP 5, PHP 7)

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, you can also 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 (if you"re familiar with C, this is the same behavior) 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 your if/elseif conditions, you must not separate else if into two words, or PHP will fail with a parse error.

/* Incorrect Method: */
if ($a > $b):
else if ($a == $b): // Will not compile.
echo "The above line causes a parse error.";
endif;

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

So, we already know how to create and display variables. We also already have a clear idea of ​​how variables interact with each other in PHP. Now it's time to move on to the very important IF-ELSE (if - otherwise) construct in PHP.

Here is the working syntax for this construction:

IF (condition) - if the condition is true, then the
{
actions
}
else - if the condition is false, then they are executed
{
actions
}
?>

Let's look at how the structure works using a specific example:

$c = 3;
$d = 5;
if ($c ==$d)
{
echo "Variables are equal";
}
else
{
echo "Variables are not equal";
}
?>

You can see that at the beginning we assigned the variables $c and $d different values. Then we set a condition and check whether these variables are equal to each other. And since they are not equal, the else part and the echo statement are triggered. That is, the result of executing this code will be the inscription on the screen - Variables are not equal. If you have any questions, ask! I will be happy to answer them.

Double IF-ELSE conditions

The syntax presented above can also be called the single-condition IF-ELSE construct. Now let’s complicate the example I presented above and add one more condition. To do this, we will create 1 more example, but we will already apply double IF-ELSE conditions.

$c = 3;
$d = 5;
$e = 8;
$k = 10;
if ($c !=$d and $e !=$k)
{
echo "Variables are not equal";
}
else
{
echo "Variables are equal";
}
?>

I would like to note that != - in php means “not equal”.
Double conditions in php are created using boolean functions:

  • and (logical and, also php allows you to write && instead of and);
  • or (logical or, php also allows you to write || instead of or).

The result of executing our program is the display of the message “Variables are not equal.”



Have questions?

Report a typo

Text that will be sent to our editors: