Table of Contents
Toggleif else statement
The if else statement executes some code if a condition is true and another code if that condition is false.
Syntax
if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
<?php
$t = date("H");
if ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>
An if-else statement in PHP allows you to execute certain code based on whether a condition is true or false. Here’s a basic example:
<?php
$number = 10;
if ($number > 0) {
echo "The number is positive.";
} elseif ($number < 0) {
echo "The number is negative.";
} else {
echo "The number is zero.";
}
?>
Explanation:
if ($number > 0): This checks if the$numberis greater than 0. If true, it will execute the code within the block.elseif ($number < 0): This checks if the$numberis less than 0, and it runs only if the first condition is false.else: If none of the above conditions are true, the code inside theelseblock is executed.
You can add multiple elseif blocks if you need to check more conditions.