Quick Contact

    Conditional Statements

    Sometimes when you write code, you want to perform different actions for different decisions. You can use conditional statements in your code to do this. Conditional statements are the set of commands used to perform different actions based on different conditions.

    Conditional statements (such as “if else” or “switch”) are used to alter the flow of a program if a specific test condition is true. Conditional statements make logical decision between various conditions based on input values. So, the conditional statements make your computer program to respond according to their inputs. Similar to other programming languages, PHP also have different types of conditional statements.

    There are several statements in PHP that you can use to make decisions:

    • The if statements
    • The if…else statement
    • The if…elseif…. else statement
    • The switch…case statement

    We will explore each of these statements in the coming sections.

    If else

    The if statement is used to execute a block of code only if the specified condition evaluates to true. This is the simplest PHP’s conditional statements and can be written like:

    if(condition){
        // Code to be executed
    }
    

    The if, else statement executes some code if a condition is true and another code if that condition is false. Two conditions can be implemented on if else statement.

    You can enhance the decision-making process by providing an alternative choice through adding an else statement to the if statement. The if…else statement allows you to execute one block of code if the specified condition is evaluates to true and another block of code if it is evaluates to false.

    It can be written, like this:

    if(condition) {
        // Code to be executed if condition is true
    } else {
        // Code to be executed if condition is false
    }
    
    Flow diagram of if else statement
    Flow diagram of if else statement
    Let’s Understand by using following Program

    The following example will output “$num is even number” if the Condition is true, Otherwise, it will output ” $num is odd number.

    <html>
    <body>
        <?php  
            $num=12;  
            if($num%2==0){  
                echo "$num is even number";  
            }else{  
                echo "$num is odd number";  
            } 
        ?>  
    </body>
    </html>
    
    Result is:

    12 is even number

    The following example will output “Have a nice weekend!” if the current day is Friday, otherwise it will output “Have a nice day!”

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <title>PHP if-else Statement</title>
    </head>
    <body>
        <?php
            $d = date("D");
            if($d == "Fri"){
                echo "Have a nice weekend!";
            } else{
                echo "Have a nice day!";
            }
        ?>
    </body>
    </html>     
    
    If else if else

    The if, elseif, else a special statement that is used to combine multiple if, else statements. elseif is a combination of if and else. It extends an if statement to execute a single statement or a group of statements if a certain condition is met. It cannot do anything if the condition is false.

    If you want to execute some code if one of the several conditions are true use the elseif statement.

    It can be written, like this:

    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;
    
    Flow diagram of if else if else statement
    Flow diagram of if else if else statement
    Let’s Understand by using following Program’

    The following example will output “Have a nice weekend!” if the current day is Friday, and “Have a nice Sunday!” if the current day is Sunday. Otherwise, it will output “Have a nice day!” :

    <html> 
    <body> 
    
      <?php
         $d = date("D");
         
         if ($d == "Fri")
            echo "Have a nice weekend!";
         
         elseif ($d == "Sun")
            echo "Have a nice Sunday!"; 
         
         else
            echo "Have a nice day!"; 
      ?> 
    </body> 
    </html> 
    
    It will produce the following result

    Have a nice Weekend!

    Nested if

    Nested if statements mean an if block inside another if block. Shortly a control structure inside another control structure.

    It structure will look like:

    if (expression 1 )
    {
    if (expression 2 )
    {
    // statements 1
    }
    else
    {
    // Statements 2
    }
    }
    else
    {
    if ( expression 2)
    {
    // Statements 3
    }
    else
    {
    // Statements 4
    }
    }
    

    Here we can see another if ,else structure inside the if block and else block. Like this we can add any number of nested if else statements.

    Switch Case

    The switch statement is used to perform different actions based on different conditions. In addition to the if statement, PHP provides switch statement that allows you to execute a code block conditionally. PHP switch statement compares a variable or an expression against many different values and execute a code block based on the value it equals to.

    The switch statement is used to avoid long blocks of if..elseif..else code.

    It structure will look like:

    <?php
    switch(variable){
     case value1: 
     // code block 1
     break;
     case value2: 
     // code block 2
     break;
     default:     
     // default code block
     break;
    }
    ?>
    

    Let’s examine the switch statement syntax in more detail:

    • First, you put a variable or expression that you want to test within parentheses after the switch keyword.
    • Second, inside the curly braces are multiple case constructs where you put the values you want to compare with the variable or expression. In case the value of the variable or expression matches the value in a case construct, the code block in the corresponding case construct will execute. If the value of the variable or expression does not match any value, the code block in the default construct will execute.
    • Third, the break statement is used in each case or default construct to exit the entire switch statement.

    It is very important to understand that the switch statement is executed statement by statement therefore the order of case constructs is very important. If the value of the variable match a value in a case construct, PHP will execute code block in that case construct and ends the switch statement because of the break statement.

    Flow diagram of switch statement
    Flow diagram of switch statement
    Let’s Understand by using following Program

    The switch statement works in an unusual way. First it evaluates given expression then seeks a lable to match the resulting value. If a matching value is found then the code associated with the matching label will be executed or if none of the lable matches then statement will execute any specified default code.

    <html>
    <body>
      <?php
         $d = date("D");
         
         switch ($d){
            case "Mon":
               echo "Today is Monday";
               break;
            
            case "Tue":
               echo "Today is Tuesday";
               break;
            
            case "Wed":
               echo "Today is Wednesday";
               break;
            
            case "Thu":
               echo "Today is Thursday";
               break;
            
            case "Fri":
               echo "Today is Friday";
               break;
            
            case "Sat":
               echo "Today is Saturday";
               break;
            
            case "Sun":
               echo "Today is Sunday";
               break;
            
            default:
               echo "Wonder which day is this ?";
         }
      ?>
    </body>
    </html>
    
    It will produce the following result:

    Today is Monday

    Jump Statements (Break, Continue, Exit)

    In PHP jump statements are mainly used to transfer control to another part of our program depending on the conditions. These statements can be used to jump directly to other statements, skip a specific statement and so on. Jump statements allow you to exit a loop, start the next iteration of a loop, or explicitly transfer program control to a specified location in your program

    Sometimes you may want to let the loops start without any condition and allow the statements inside the brackets to decide when to exit the loop. There are three special statements that can be used inside loops: Break, Continue and Exit which are discussed in the following sections.

    Break Statement:

    Break ends execution of the current structure. Break accepts an optional numeric argument which tells it how many executions of nested structures to be interrupted.

    Uses of Break:
    • A break statement can be used to terminate or to come out from the loop or conditional statement unconditionally.
    • It can be used in switch statement to break and come out from the switch statement after each case expression.
    • Whenever, break statement is encounter within the program then it will break the current loop or block.
    • A break statement is normally used with if statement.
    Let’s Understand by using following Program

    The following program demonstrates the use of break statement. Loop will be terminated as soon as the counter value becomes greater than 5.

    <?php
       for( $i = 1; $i <= 10 ; $i++ )
       {
            if ($i > 5)
                break;    // terminate loop 
            echo "$i"."" ;
       }
    ?>
    
    Example with argument:
    <?php
       $x = 2 ;
       while($x)
       {
            for($j =0 ; $j ++)
            {
                echo $j * $x ;
              
                if($j * $x >= 10)
                {
                    break 2;
                }
                
            }
          $x ++ ;
       }
    
    Output of code

    0 2 4 6 8 10

    Continue Statements:

    A continue statement can be used into the loop when we want to skip some statement to be executed and continue the execution of above statement based on some specific condition. Similar to break statement, continue is also used with if statement. When compiler encounters continue, statements after continue are skipped and control transfers to the statement above continue.

    Continue Statements
    Let’s Understand by using following Program

    The following example uses the continue statement to print upper and lower a to z alphabets:

    <?php
       for ( $i = 65 ; $i <= 122 ; $i++ )   // loop through ASCII value for a to z
       {
           if($i >= 91 && $i <= 96)
                  continue ;       // skip unnecessary special characters.
           
              echo "| $i "."</br>" ;   // print character equivalent for ASCII value. 
       }
    ?>
    

    In the following example, the list of odd numbers between 1 to 10 have printed. In the while loop we test the remainder (here $x%2) of every number, if the remainder is 0 then it becomes an even number and to avoid printing of even numbers continue statement is immediately used and the control passes to the beginning of the loop.

    <?php
    $x=1;
    echo 'List of odd numbers between 1 to 10 <br />';
    while ($x<=10)
    {
    if (($x % 2)==0)
    {
    $x++;
    continue;
    }
    else
    {
    echo $x.'<br />';
    $x++;
    }
    }
    
    Output:

    List of odd numbers between 1 to 10

    1
    3
    5
    7
    9

    Exit Statement:

    The exit () function terminates execution of the script. It prints status just before exiting. Exit Output a message and terminate the current script.

    The exit () function prints a message and exits the current script.

    This function is an alias of the die() function.

    Syntax:

    xexit(message)

    Message Description

    Specifies the message or status number to write before exiting the script. The status number will not be written to the output.

    Example

    Print a message and exit the current script:

    <?php
    $site = "https://www.w3schools.com/";
    fopen($site,"r")
    or exit("Unable to connect to $site");
    ?>
    
    Parameters:
    void exit ([ string $status ] )
    void exit ( int $status )
    

    status

    • If status is a string, this function prints the status just before exiting.
    • If status is an integer, that value will be used as the exit status and not printed. Exit statuses should be in the range 0 to 254, the exit status 255 is reserved by PHP and shall not be used. The status 0 is used to terminate the program successfully.
    Return Values

    No value is returned.

    exit status example
    <?php
    //exit program normally
    exit;
    exit();
    exit(0);
    //exit with an error code
    exit(1);
    exit(0376); //octal
    ?>
    
    Summary
    • The conditional statements make your computer program to respond according to their inputs
    • if statement: executes some code if one condition is true.
    • if else statement: executes some code if a condition is true and another code if that condition is false.
    • If, elseif, else statement: executes different codes for more than two conditions.
    • switch statement: selects one of many blocks of code to be executed.
    • Jump statements can be used to jump directly to other statements, skip a specific statement and so on.

    Copyright 1999- Ducat Creative, All rights reserved.