If else in PHP

In PHP, the if statement is used to execute a block of code if a specified condition evaluates to true. You can also use the else statement to execute a different block of code if the condition evaluates to false. Here's the basic syntax for the if statement:

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

If the condition inside the parentheses evaluates to true, the code block inside the first set of curly braces {} is executed. If the condition is false, the code block inside the else statement (if present) is executed.

$age = 25;

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

In this example, if the variable $age is greater than or equal to 18, the message "You are an adult." will be echoed. Otherwise, the message "You are not yet an adult." will be echoed.

You can also use the elseif statement to check multiple conditions sequentially. Here's the syntax:

if (condition1) {
    // Code to be executed if condition1 is true
} elseif (condition2) {
    // Code to be executed if condition1 is false and condition2 is true
} else {
    // Code to be executed if both condition1 and condition2 are false
}

Here's an example using elseif:

$grade = 75;

    if ($grade >= 90) {
        echo "A";
    } elseif ($grade >= 80) {
        echo "B";
    } elseif ($grade >= 70) {
        echo "C";
    } elseif ($grade >= 60) {
        echo "D";
    } else {
        echo "F";
    }

In this example, the script checks the value of $grade and echoes the corresponding letter grade based on the specified conditions.

Next Article ❯