if...else..elseif

PHP if else statement is used to test condition. You want to perform different actions for different conditions. You can use conditional statements in your code to do this.

There are various ways to use if statement in PHP.

  1. if statement - executes some code if one condition is true
  2. if...else statement - executes some code if a condition is true and another code if that condition is false
  3. if...elseif...else statement - executes different codes for more than two conditions
  4. switch statement - selects one of many blocks of code to be executed

PHP - if statement

The if statement allows you to execute a statement if an expression evaluates to true. The following shows the syntax of the if statement:

Example

if(condition)
{
    // if TRUE then execute this code
}

 

PHP - The if...else Statement

PHP if-else statement is executed whether condition is true or false.

If-else statement is slightly different from if statement. It executes one block of code if the specified condition is true and another block of code if the condition is false.

Example

if(condition)
{  
   //code to be executed if true  
}
else
{  
   //code to be executed if false  
}  

 

PHP - The if…elseif…else Statement

This allows us to use multiple if…else statements. We use this when there are multiple conditions of TRUE cases.

Example:

if(condition) 
{
    // if TRUE then execute this code
}
elseif 
{
    // if TRUE then execute this code
}
elseif 
{
    // if TRUE then execute this code
}
else 
{
    // if FALSE then execute this code
}

 

PHP - Switch Statement

PHP switch statement is used to execute one statement from multiple conditions. It works like PHP if-else-if statement.

To use switch, we need to get familiar with two different keywords namely, break and default.

  1. The break statement is used to stop the automatic control flow into the next cases and exit from the switch case.
  2. The default statement contains the code that would execute if none of the cases match.

Example

switch(n){
    case statement1:
        code to be executed if n==statement1;
        break;
    case statement2:
        code to be executed if n==statement2;
        break;
    case statement3:
        code to be executed if n==statement3;
        break;
    case statement4:
        code to be executed if n==statement4;
        break;
    ......
    default:
        code to be executed if n != any case;