• Conditional if statement in PHP. PHP if-else. Conditions in PHP Php if else examples

    if construct

    Construction syntax if similar design if in C language:

    if (boolean expression) statement;
    ?>

    According to PHP expressions, the construction if contains a Boolean expression. If the Boolean expression is true ( true), then the operator following the construction if will be executed, and if the logical expression is false ( false), then the next one after if the statement will not be executed. Here are some examples:

    if ($a > $b) echo "the value of a is greater than b";
    ?>

    In the following example, if the variable $a is not equal to zero, the string “the value of a is true” will be printed:

    if ($a) echo "the value of a is true ";
    ?>

    In the following example, if $a is null, the string "the value of a is false" will be printed:

    if (!$a ) echo "the value of a is false ";
    ?>

    Often you will need a block of statements that will be executed under a certain conditional criterion, then these statements will need to be placed in curly braces {...} Example:

    if ($a > $b) (
    echo "a is greater than b" ;
    $b = $a ;
    }
    ?>

    The above example will display the message, "a is greater than b" if $a > $b and then the variable $a will be equated to a variable $b. Note that these operators are executed in if.

    if (boolean_expression):
    teams;
    elseif(other_logical_expression):
    other_commands;
    else:
    else_commands;
    endif

    Pay attention to the placement of the colon ( : )! If you skip it, an error message will be generated. And one more thing: as usual, blocks elseif And else can be omitted.

    elseif construct

    elseif is a combination of designs if And else. This construction extends the conditional construction if-else.

    Here is the syntax of the construction: elseif:

    if (boolean_expression_1)
    operator_1;
    elseif (boolean_expression_2)
    operator_2;
    else
    operator_3;

    Practical example of using the design elseif:

    if ($a > $b) (
    echo "a is greater than b" ;
    ) elseif ($a == $b ) (
    echo "a is equal to b" ;
    ) else (
    echo "a is less than b" ;
    }
    ?>


    The main thing in the action of this operator is the condition. if translated from English means If. The condition is accepted as an argument (what is in parentheses). The condition can be a logical expression or a logical variable. To put it simply, the meaning of the expression will be this:

    If (condition)(
    the condition is met, do this
    }
    else
    {
    the condition is not met, do it differently
    }
    I hope the logic of the conditional operation is clear. Now let's look at an example.

    $a = 5;
    $b = 25;

    // Now attention! Condition: If $b is greater than $a
    // Signs > and< , как и в математике, обозначают больше и меньше
    if($b > $a)
    {
    // if the condition is met, then perform this action
    echo "$b is greater than $a";
    }
    else
    {
    // if not executed, then this
    echo "$a is greater than or equal to $b";
    }
    ?>
    Demonstration Download sources
    As a result, the script will output 25 more than 5. The example is quite simple. I hope everything is clear. Now I propose to consider a more complicated situation, where several conditions must be met. Each new condition will contain after the main condition if()- auxiliary, which is written as else if(). In the end it will be as usual else.

    Task: Testing is carried out at school. The script needs to calculate the score, knowing the conditions for obtaining each grade and the student’s score itself. Let's see how to write this, and don't forget to read the commentary.

    $test = 82; // let's say a student wrote a test with 82 points

    // write the first condition for five
    if($test > 90)
    {
    // if the condition is met, then perform this action.
    echo "Rating 5";
    }
    // The && sign means "and, union", that the condition is met if both are true
    // that is, the score is less than 91 and more than 80, then 4. Otherwise, the conditions are read further
    else if ($test< 91 && $test > 80)
    {
    echo "Rating 4";
    }
    else if ($test< 81 && $test > 70)
    {
    echo "Rating 3";
    }
    else
    {
    echo "We should write the test again...";
    }
    ?>
    Demonstration Download sources
    Our student who has time to both rest and write a normal test receives rating 4! I hope the principle of operation is clear.

    It is also possible to briefly record the operation of a conditional operation, when you need an action only if the condition is met.

    $age = 19; // variable with age

    If ($age > 17)(
    echo "That's it! I can do whatever I want! I'm already $age!";
    }
    Quite a nice example of a short notation of a conditional operation. else it is not necessary to write.

    Comparison Operators in PHP

    The principle of operation of a conditional operation is clear. But, as you understand, there are many more ways to compare. Let's look at the table below with comparison operators.

    Example Name Result
    $a == $b Equals True if $a equals $b
    $a === $b Identical to True if $a is equal to $b and both variables are of the same type
    $a != $b Not equal to True if $a is not equal to $b
    $a === $b Not identical to True if $a is not equal to $b and both types are not the same
    $a > $b Greater than True if $a is greater than $b
    $a< $b Меньше чем True, если $a меньше, чем $b
    $a >= $b Greater than or equal to True if $a is greater than or equal to $b
    $a<= $b Меньше или равно True, если $a меньше или равно $b
    Now let's look at the operators with examples:

    // contrary to habit = means assigning a value to a variable, and == is equal
    if ($a == 5)(
    echo "$a is 5"; // will print "5 equals 5"
    ) else (
    echo "$a is not equal to 5";
    }

    If ($a != 6)(
    echo "$a is not equal to 6"; // will print "5 is not equal to 6". Necessary in case of denial
    ) else (
    echo "$a somehow equals 6";
    }

    // with more and less I think everything is clear. Therefore the example is more complicated
    if ($a<= 6){
    echo "$a is less than or equal to 6"; // will print "5 is less than or equal to 6"
    ) else (
    echo "$a is greater than 6";
    }

    PHP Logical Operators

    There are times when you need to compare not one variable, but two or more at once in one condition. For this there are logical operators.

    Example Name Result
    $a and $b Logical "and" TRUE if both $a and $b are TRUE.
    $a or $b Logical "or" TRUE if either $a or $b is TRUE.
    $a xor $b Exclusive "or" TRUE if $a or $b is TRUE, but not both.
    ! $a Negation of TRUE if $a is not TRUE.
    $a && $b Logical "and" TRUE if both $a and $b are TRUE.
    $a || $b Boolean "or" TRUE if either $a or $b is TRUE.
    We have already noticed that for operations And And or are there additional operators? This is done in order to prioritize complex comparison operations. In the table, logical operators are listed in order of priority: from least to greatest, that is, for example, || has higher priority than or.

    Let's move on to examples

    $a = 5;
    $b = 6;
    $c = 7;

    // condition: If 5 is not equal to 6 (TRUE) AND 6 is not equal to 7 (TRUE)
    if ($a< 6 && $b != $c){
    echo "Indeed so!"; // will print "Indeed so!" because BOTH conditions are TRUE
    ) else (
    echo "One of the conditions is not true";
    }

    // condition: If 6 is not equal to 6 (FALSE) OR 6 is not equal to 7 (TRUE)
    if ($b != 6 || $b != $c)(
    echo "That's it!"; // will display "That's it!", because at least ONE of the conditions is TRUE
    ) else (
    echo "Both conditions are false";
    }

    Ternary operator

    I suggest you return to the issue of ternary code later. I couldn’t help but mention it, since it’s an important design that significantly reduces the code size. I suggest you look at the code right away.

    The gist of the code:(condition) ? the value of a if true: the value of a if false

    Thus, we shorten the if statement. However, this operation is only valid when assigning values ​​to a variable. Now let's look at a finished example.

    // Example of using the ternary operator
    $settings = (empty($_POST["settings"])) ? "Default" : $_POST["settings"];

    // The above code is similar to the following block using if/else
    if (empty($_POST["settings"])) (
    $settings = "Default"; // If nothing is transferred, then leave it as "Default"
    ) else (
    $settings = $_POST["settings"]; // If passed, then $settings is assigned the passed value.
    }
    ?>
    Read the comments to the code and everything should be clear.

    Thank you for your attention!


    Like other programming languages, PHP has selection statements. There are three types in total:

    • conditional statement if...else ;
    • switch switch ;
    • conditional operation (? );

    It is worth noting that in PHP there is no unconditional jump on the goto label, but despite this, the goto keyword is reserved.

    In this lesson we will look at the if...else statement and conditional operations, and the next lesson will cover the switch switch.

    The if...else syntax is the same as in C:

    //if uslovie is true, then we get here operator1; //in the case of one operator, operator2; ... ) else // optional {//if uslovie is false, then we go here operator3; //in the case of one operator, operator4; //curly braces are optional ... } ?>

    Notes:

    • else is not a required part, but it is most often used because Logic demands it.
    • As noted in the code comments, curly braces () are not necessary if we only have one statement. Since the condition can be either true (1) or false (0), either operator1, operator2, etc., or operator3, operator4, etc. will be executed.

    Here's a specific example in PHP:

    //Set variable values$num1 = 10; $num2 = 7; if ($num1 > $num2) ( //the condition is true, which means we get here echo "The condition is true because 10 > 7
    "; $num1+=$num2; // add the variable $num2 to $num1; echo "\$num1 = ". $num1; // the result will be 17) else echo "Since the condition is positive, we don't get here"; // There is only one else statement, so there are no curly braces ?>

    Here's an example in which the else clause is omitted and the condition consists of two conditions:

    6) echo "Conditions are true"; //Another example: if ($num1 == 10 || $num2 >= 100) echo "The conditions are true"; //In all cases the conditions are true ?>

    Nested if conditions

    As in the C language, PHP allows the use of nested conditions:

    //if uslovie1 and uslovie2 are true, then we get here) else ( //if uslovie1 is true and uslovie2 is false, then we get here) else ( //if uslovie1 and uslovie2 are false, then we get here } ?>

    You can write as many if nestings in if as you like, but such constructions are very complex, so it will be quite difficult to understand them when debugging a program. Here's an example with nested if statements:

    // the result of this script will be a message: // $flag1 is true and $flag2 is false ?>

    Nesting conditions using if...elseif...else

    PHP has the ability to nest conditional statements using the scheme: if...elseif...else . This is much more convenient than initially making a set of conditions, and then adding a set of else to them. The syntax of the if...elseif...else construct is as follows:

    In such a construction, else can be written only once, but elseif can be written as many times as you like. It is also considered that the above design is inferior to the switch switch.

    Using the endif operator

    Almost any engine created in PHP uses the endif operator. The construction of this operator is shown below:

    ... html tags and content; ... ... html tags and content; ...

    It is worth paying attention to the convenience of this design than if we output all content through echo . Don't forget to put a colon after the condition!

    Using conditional operators (?)

    The use of conditional operators is not a common approach not only in PHP, but also in other similar languages, but they should not be forgotten. The syntax of the conditional operation is as follows:

    First comes some condition. If it is true, then operator_1 is executed, otherwise operator_2 is executed. I think the construction is not very clear, so it's worth giving a couple of PHP examples to clarify. For example, using a conditional operator, you can easily implement the modulus of a number:

    Conditional operations can be advantageous to use in some short expressions where you need to change the value of only one variable depending on a condition.

    (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;

    12.09.2017

    Not yet


    Hi all!
    Let's continue to learn the basics of PHP from scratch!
    In this lesson I will tell you about conditional statement if else. Literally translated, if means “if”, and else means “otherwise”. The if else construct itself helps to verify data and display the result (display messages, execute some command, redirect the user to a secret page or let him into the admin panel). To learn how to write conditions correctly and understand the if else construct, I will give a real-life example that is very similar to the if else construct.
    You give your brain a command: as soon as the alarm clock sounds (6:00), I must get up, wash my face, brush my teeth, get dressed and gallop to work. If the alarm clock doesn't ring at 6:00, then you can sleep, since you don't have to run to work.
    Did you notice the if else construct? The condition 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 tell lies), then we continue to sleep.
    There are a lot of such life examples, for example: if it rains, then I sit at home, if it doesn’t rain, then I take the ball and go play football.
    So how can you write the if else construct? Very simple.
    Let's go step by step and start with a simple condition - the if statement.

    For better understanding, I have depicted the if construct diagram as a picture:

    Now let's try to transform the real-life example that I provided above into php code.

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

    ⇒ Code explanation:
    In the condition, I compared the $weather variable with the value "rain" (line #3). In human language, this code looks like this: if the variable $weather is equal to the value "rain", then you need to print the text " I'm sitting at home". By the way, let me remind you (if you forgot) that the equal sign is indicated by a double equal sign, like this (==). If you write another value to the $weather variable (line No. 2), for example, snow, then the browser will blank page because the conditions were not met.

    → TEMPLATE CODE "if CONSTRUCTION":

    → Cheat sheet:

    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 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 let's try to display a message if the conditions have not been met, namely, if it rains, I sit at home, if it doesn't rain, I take the ball and go play football. For a better understanding, let's look at the picture below:

    Now let’s translate the diagram into real code:

    Result:

    I take the ball and go play football

    ⇒ Code explanation:
    In the condition, I compared the $weather variable with the value “rain” (line No. 3), but since I assigned the value “sun” to the $weather variable (line No. 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 play football"; //result if the condition is not true)

    → TEMPLATE CODE "if-else CONSTRUCTION":

    Double if-else condition

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

    Target:
    Create a login and password verification condition. If the password or login does 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 two variables with the "AND" operator. This means that two variables must be correct for the condition to be fulfilled, but since the password in our condition does not match (sink No. 4), it means that the condition is incorrect and you will see this message on the screen:

    Login or password is incorrect

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

    Result:

    welcome to the admin panel

    Nested if-else constructs

    Nesting- this is when there is another structure inside the structure. Didn't explain it quite clearly? It doesn’t matter, you’ll understand everything with an example.

    Target:
    Create a login and password verification condition. If the password or login does 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 the 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 check the $logo and $password variables:

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

    Since the secret word is incorrect (line No. 8), the message will appear on the screen:

    secret word is wrong

    If you replace the value of $x with "BlogGOOD", then the secret word will be true:

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

    welcome to the admin panel

    → TEMPLATE CODE "NESTED if-else CONSTRUCT":

    elseif conditional operator

    elseif construct is a combination of if and else constructs that will help check several conditions in a row.

    Syntax:

    Please note that in lines No. 6 and No. 10 two words are specially written together “elseif”; if you separate them with a space “else if”, the code will generate an error.

    Let me show you the working code with a selection of programming textbooks.

    Result:

    You ordered a PHP tutorial

    The elseif method can also be written as nested if else construct:

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

    Addition to the lesson (not necessary to know yet):

    There are several more options for writing the if else ( alternative syntax).
    I will prepare a whole lesson about alternative syntax, where I will explain and show everything. Now just take a look.
    Code No. 1:

    The variable "$a" contains the value 15

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

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

    That's it, I'm looking forward to seeing you in the next lessons! Subscribe to blog updates!

    Previous post
    Next entry