PHP “if”, “else” and “elseif” Statements

In PHP, if, else, and elseif statements are used to control the flow of a program based on conditional logic. Conditional statements allow you to specify certain conditions that must be met in order for the program to execute certain blocks of code.

Here is an example of using if, else, and elseif statements in PHP:





$num = 5;
if ($num < 0) {
    echo "Number is negative";
} elseif ($num == 0) {
    echo "Number is zero";
} else {
    echo "Number is positive";
}

In this example, the variable $num is assigned the value 5. The if statement checks if the value of $num is less than zero. If it is, the string “Number is negative” is printed to the screen. If the first condition is not true, the elseif statement checks if the value of $num is equal to zero. If it is, the string “Number is zero” is printed to the screen. If both the if and elseif statements are not true, the else statement executes and the string “Number is positive” is printed to the screen.

You can also use logical operators to create more complex conditional statements:





$num1 = 5;
$num2 = 3;
if ($num1 > 0 && $num2 > 0) {
    echo "Both numbers are positive";
} elseif ($num1 < 0 || $num2 < 0) {
    echo "At least one number is negative";
} else {
    echo "Neither number is positive or negative";
}

In this example, the variables $num1 and $num2 are assigned the values 5 and 3, respectively. The if statement checks if both $num1 and $num2 are greater than zero. If they are, the string “Both numbers are positive” is printed to the screen. If the if condition is not true, the elseif statement checks if either $num1 or $num2 is less than zero. If either condition is true, the string “At least one number is negative” is printed to the screen. If both the if and elseif statements are not true, the else statement executes and the string “Neither number is positive or negative” is printed to the screen.

By using if, else, and elseif statements in PHP, you can create conditional logic that allows your program to make decisions and execute different blocks of code based on certain conditions.