PHP if..else..else if Statement

In PHP, the if...else...else if statement is used for conditional branching, allowing you to execute different blocks of code based on different conditions. Here’s the syntax for the if...else...else if statement:

if (condition1) {
    // Code to execute if condition1 is true
} elseif (condition2) {
    // Code to execute if condition2 is true
} else {
    // Code to execute if none of the conditions are true
}

Here’s an example that demonstrates the usage of if...else...else if statement in PHP:

$age = 25;

if ($age < 18) {
    echo "You are underage.";
} elseif ($age >= 18 && $age < 65) {
    echo "You are an adult.";
} else {
    echo "You are a senior citizen.";
}

In this example, the code checks the value of the variable $age. If the age is less than 18, it prints “You are underage.” If the age is between 18 and 64 (inclusive), it prints “You are an adult.” Otherwise, if none of the conditions are true, it prints “You are a senior citizen.”

Some important points to note about the if...else...else if statement:

  1. The if the block is mandatory, but the else and else if blocks are optional.
  2. Multiple elseif blocks can be used to test additional conditions.
  3. Conditions can include logical operators (&& for “and”, || for “or”, ! for “not”), comparison operators (<, >, ==, !=, etc.), and other expressions that evaluate boolean values.
  4. The else the block is executed only if none of the previous conditions are true.
  5. The else block can be used as a fallback for handling any unexpected or default scenarios.

The if...else...else if statement is a powerful construct in PHP that allows you to handle multiple conditions and control the flow of your program based on those conditions. It provides flexibility in executing different blocks of code based on different scenarios.