WS WhereIsStuff
Tutorial Guides
Log In
Sign Up

Advertisement

Google Ad Slot: content-top

PHP if...else Statements


PHP - The if...else Statement


if...else statements allow you to execute a block of code based on whether a condition evaluates to true or false. The if part handles the condition you want to check, and the else part provides an alternative set of code to execute when the if condition is not met.


Syntax of if...else


if (condition) {
    // Code to be executed if condition is true
} else {
    // Code to be executed if condition is false
}
Example
<?php
$age = 16;

if ($age >= 18) {
echo "You are eligible to vote.";
} else {
echo "You are not eligible to vote.";
}
?>
Try it yourself

PHP - The if...elseif...else Statement


if...elseif...else statements in PHP allow you to evaluate multiple conditions in a sequential manner. When a condition is met (i.e., evaluates to true), the corresponding block of code is executed, and the remaining elseif or else blocks are skipped. This is useful for implementing complex conditional logic.


Syntax of if...elseif...else


if (condition1) {
    // Code to be executed if condition1 is true
} elseif (condition2) {
    // Code to be executed if condition2 is true
} elseif (condition3) {
    // Code to be executed if condition3 is true
} else {
    // Code to be executed if all conditions are false
}
Example
<?php
$time = 15;

if ($time < 12) {
echo "Good morning!";
} elseif ($time < 18) {
echo "Good afternoon!";
} elseif ($time < 22) {
echo "Good evening!";
} else {
echo "Good night!";
}
?>
Try it yourself