PHP Decision Making Statement - if...else

Decision making statments are used to take decision, which code is to be executed, based on the specified condition. Decision making statements are also known as conditional statements. PHP supports following types decision making statements:

  1. if statement: Executes block of code, only if specified condition is true.
  2. if...else statement: Use this statement if you want to execute block of code when a condition is true and another block of code, if the condition is not true.
  3. if...elseif statement: It is like a nested if else statement, which have multiple conditions, out of which only one condition will execute a block of statements associated with the true condition.
  4. switch statement: If you want to create a choice menu based program than use switch statement. It select one or more out of many blocks of code based on the value match. The advantage of switch statement is to avoid long blocks of if..elseif statement.

PHP if Statement

Example 1: If condition.

<html>
    <body>
        <?php
            $d=date("D");
            if ($d=="Sun")
                echo "Happy Sunday!"; 
        ?>
    </body>
</html>
In above code, if the date("D") function, returns day as 'Sun' then it print 'Happy Sunday!

PHP if...else Statement

Example 2: Fetch current day and check it is sunday or not using if...else

<html>
    <body>
        <?php
            $d=date("D");
            if ($d=="Sun") // for one line statement curly bracket is optional
                echo "Happy Sunday!";
            else
                echo "Its a working day";
        ?>
    </body>
</html>
Above code, if the condition is true it display 'Happy Sunday!' otherwise it display 'Its a working day'.

PHP if...else Statement

Example 3: Fetch current day and check it is sunday, saturday or any other day using if...else if statement

<html>
    <body>
        <?php
            $d=date("D");
            if ($d=="Sun")
                echo "Happy Sunday!";
            else
            { //curly brackets define the block
                if($d=="Sat")
                    echo "Its a Half day";
                else
                    echo "Working Day"
            }
        ?>
    </body>
</html>
Above code will check if condition, if it is true display 'Happy Sunday!' else check for another condition for Saturday, if it is false then else statement will execute 'Working day'.

Exercise Questions: PHP Decision Making | if condition

  1. If current time is less than 12 display good morning, if current time is less than 20 display Good Day, else print Good Night. Hint: For time use PHP time function ($t = date("H");).