Php Conditional Statements

In PHP following conditional statements are available:
  • if statement - this statement executes some code only if a specified condition is true
  • <html>
    <body>
    <?php
    
    $var="hello";
    
    if ($var=="hello") echo $var;
    
    ?>
    </body>
    </html>
    Result:hello 
    
  • if...else statement - this statement executes some code if a condition is true and another code if the condition is false
  • <html>
    <body>
    <?php
    $var="hello";
    if ($var!="hello")
    {
      echo $var; 
    }
    else
     {
      echo "this block is executed"; 
    }
    ?>
    </body>
    </html>
    Result:this block is executed 
    
  • if...elseif....else statement - this statement used to execute one of several parts of code to be execute.
  • <html>
    <body>
    <?php
    $d=date("D");
    if ($var=="hello")
      {
       echo "this block is executed"; 
      }
    if ($var=="welcome")
      {
      echo "test code";
      }
    else
      {
       echo "test code"; 
      }
    ?>
    </body>
    </html>
    Result:this block is executed 
    
  • switch statement - use this statement to select one of many blocks of code to be executed
  • <html>
    <body>
    <?php
    
    $var=100;
    switch ($var)
    {
    case 1:
      echo "Number 100";
      break;
    
    case 2:
      echo "Number 200";
      break;
    
    case 3:
      echo "Number 300";
      break;
    
    default:
      echo "No number between 100 and 300";
    }
    ?>
    </body>
    </html>
    Result:Number 100 

No comments: