PHP Control Structure -if...else..elseif Statements

Techno PHP

PHP Decision Making

Decision making means you have to take a decision for you work code.If you have need that my application print this statement when anyone user login and if user does not enter password or userid so print another statement(enter your username and password).

In simple words, if your condition is true (according to your need ) then execute this code and if your condition is not true then your code is not executed ( or print another statement) There are various type of decision-making structure.

  • if statement

  • if else statement

  • if...elseif....else statement (Nested if else)

  • switch statement

  • Conditional statements are used in your code to take decisions .

    PHP if statement:-

    if statement is used when the one condition is true .(Only one statement ) .

    Syntax

    
    if (condition) {
       Statement (Code will be executed when condition is true);
    }
    		
    		
    

    I will show you ,how to use if condition , The example below will output "x is Greater" if the x is lessthan(<) 40.

    Example

    <?php
    $x = 20;
    
    if ($x < "40") {
        echo "X is greater";
    }?>
    Run

    The if else Statement

    In if else statement there are two types of states if one is true a statement(code) will execute and another when condition is false then another statement will execute .

    In simple word - When condition is true a code will execute and else another code will execute .

    Syntax

    if (condition)
    code to be executed if condition is true;
    else
    code to be executed if condition is false;

    The following example will output " Y is Greater" if the condition is true, otherwise(else) it will output "X is Greater ":

    Example

    <?php
    $x=30;
    $y=20;
    if ($x<$y)
    echo "Y is greater";
    else
    echo "X is Greater ";
    ?>
    Run

    PHP - The if..elseif...else Statement(Nested ifelse)

    If you have need to use two or more if else conditions then you can use the if..elseif...else Statement. If you want to execute some code if one of the several conditions is true, then use them if..elseif...else Statement .

    Syntax

    if (condition)
    
    if (condition)
    code to be executed if condition is true;
    elseif (condition)
    code to be executed if condition is true;
    else
    code to be executed if condition is false;
    

    The below example will output "Have a nice Friday " if the current day is Friday, and "Have a nice Sunday!" if the current day is Sunday. Otherwise, it will output "Have a good day.

    Example

    <?php
    $day=date("day");
    if ($day=="Fri")
    echo "Have a nice Friday ";
    
    elseif ($day=="Sun")
    echo "Have a happy Sunday";
    else
    echo "Have a good day";
    ?>
    Run

Related