PHP Conditional Statements

PHP Conditional Statements
  • Conditional statements are used to perform different actions based on conditions.
  • In PHP the following conditional statements is given below.
  • PHP if statement
  • PHP if....else statement
  • PHP if...elseif...else statement
  • PHP switch statement
PHP if statement
  • PHP if statement is used to conditional output of code. It is executed if condition is true.
  • syntax
  • if (condition) {
    //write a code to be executed
    }

  • example
  • <!DOCTYPE html>
    <html>
    <body>
    
    <?php
    $a=24;
    $b=50;
    if ($a < $b) {
    echo "a is less than b";
    }
    ?>
    
    </body>
    </html>
    
PHP if...else statement
  • If you want to output some code if a condition is true and another code if a condition is false, use the if....else statement.
  • syntax
  • if (condition) {
    //write a code to be executed
    }else {
    //write a code to be executed
    }

  • example
  • <!DOCTYPE html>
    <html>
    <body>
    <?php
    $age = 20;
    if ($age > "18") {
    echo "you are eligible for voting";
    } else {
    echo "you not are eligible for voting";
    }
    ?>
    </body>
    </html>
    
PHP if...elseif...else statement
  • If you want to output some code if one of the several conditions are true use the elseif statement
  • syntax
  • if (condition) {
    //code to be executed if condition 1 is true
    } elseif (condition) {
    //code to be executed if condition 2 is true
    } else {
    //code to be executed if all given conditions are false
    }

  • example
  • <!DOCTYPE html>
    <html>
    <body>
    <?php
    $no = 10;
    if ($no > "0") {
    echo "Positive number";
    }
    else if($no == "0"){
    echo "Number is zero";
    }
    else {
    echo "Negative number";
    }
    ?>
    </body>
    </html>
    


PHP nested if Statement
  • The nested if statement contains the if block inside another if block.
  • The inner if statement executes only when a specified condition in outer if a statement is true, then the inner condition executes.
  • syntax
  • if (condition)
    {
    if (condition) {
    //write a code to be executed
    }
    else {
    //write a code to be executed
    }
    }

  • example
  • <!DOCTYPE html>
    <html>
    <body>
    
    <?php
    $age = 20;
    $nationality = "Indian";
    if ($nationality == "Indian")
    {
    if ($age > "18") {
    echo "you are eligible for voting";
    } else {
    echo "you are not eligible for voting";
    }
    }
    else{
    echo "Nationality is not indian";
    }
    ?>
    
    </body>
    </html>
    
PHP switch statement
  • PHP switch statement is in details in next page.
Related Posts :