PHP : if Statements

In PHP, the if statement is used to execute a block of code based on the evaluation of a condition. If the condition evaluates to true, the code block associated with the if statement is executed; otherwise, it is skipped. Optionally, you can include elseif and else blocks to handle additional conditions. Here's the basic syntax of the if statement:


if (condition) {
    // Code to be executed if condition is true
} elseif (condition2) {
    // Code to be executed if condition2 is true
} else {
    // Code to be executed if all conditions are false
}

 

  • condition: An expression that evaluates to either true or false.
  • condition2: An additional condition to be evaluated if the first condition is false.

Example:


$age = 20;

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

 

In this example:

  • If the $age is less than 18, it outputs You are a minor.
  • If the $age is between 18 and 64 (inclusive), it outputs You are an adult.
  • If the $age is 65 or older, it outputs You are a senior citizen.

You can nest if statements within each other to handle more complex conditions. Additionally, you can use logical operators (`&&`, `||`, `!`) to combine multiple conditions within a single if statement. The elseif and else blocks are optional, so you can use only the if block if you only need to check one condition.