PHP : if...else Statements

In PHP, the if...else statement is used to execute different blocks of code based on the evaluation of a condition. If the condition specified in the if statement evaluates to true, the code block associated with the if statement is executed; otherwise, if the condition evaluates to false, the code block associated with the else statement is executed. Here's the basic syntax of the if...else statement:


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

 

  • condition: An expression that evaluates to either true or false.

Example:


$age = 20;

if ($age >= 18) {
    echo "You are an adult.";
} else {
    echo "You are a minor.";
}

 

In this example:

  • If the $age is greater than or equal to 18, it outputs You are an adult.
  • If the $age is less than 18, it outputs You are a minor.

You can include multiple if...else statements to handle different conditions. Additionally, you can nest if...else statements within each other to handle more complex conditions. The else block is optional, so you can use only the if block if you only need to check one condition.