login

PHP If Statement

If statement is a branching statement. If statement allows program to make decision based on one ore more specific conditions. The most basic form of the If statement is as follows:

<?php
   // if statement
   if(boolean_condition){
       // code block to be executed
   }
?>

The boolean condition after If keyword can be true or false. The code block inside If statement is executed if the boolean condition is true. We can see it visually in the flowchart follows:

Here is a simple example of using If statement. We have variable x with value is 11. In the If statement, we check if value of x is greater than 10 we print a message.

 <?php
    $x = 11;
    if($x > 10){
        echo "$x is greater than 10";
    }
 ?>

The another form of the if statement is if-else statement. If-else statement allows program execute a code block if the condition is true and execute another code block if the condition is false. The form of if-else statement is as follows:

<?php
   // if statement
   if(boolean_condition){
       // code block of if branch
       // to be executed
   }else{
       // code block of else branch
       // to be executed
   }
?>

If the boolean condition is true the code block after if branch is executed otherwise the code block of else branch is executed. Here is an example of using if-else statement. We again have a variable x with the value 0. In the if-else statement, we check if value of x is greater than 10, we print the message to indicate that otherwise we print the message to indicate x is less than 10.

<?php
   $x = 11;
   if($x > 10){
       echo "$x is greater than 10";
   }else{
       echo "$x is less than 10";
   }
?>

If you have more than one boolean conditions to check you can use if-elseif statement. Here is the form of if-elseif statement:

<?php
   // if statement
   if(boolean_condition){
       // code block of if branch
       // to be executed
   }elseif(another_bolean_condition){
       // code block of elseif branch
       // to be executed
   }else{
       // code block of elseif branch
       // to be executed
   }
?>

Here is an example of using if-elseif statement:

<?php
   $x = 0;
   if($x > 0){
       echo "$x is greater than zero";
   }elseif($x == 0){
       echo "$x is zero";
   }else{
       echo "$x is less than zero";
   }
?>

If statement can be nested infinitely within another if statement. This allows you to have a complete flexibility in controlling conditional execution of code.