Conditional statements are used to perform different actions based on different conditions. They are the heart of dynamic programming, allowing your website to respond differently to different users or data.
The if statement executes some code ONLY if a specified condition is true.
<?php
$t = date("H"); // Get current hour
if ($t < "20") {
echo "Have a good day!";
}
?>
Use the if...else statement to execute some code if a condition is true and another code if that condition is false.
<?php
$t = date("H");
if ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>
When you have more than two possible outcomes, use the elseif statement. You can have as many elseif blocks as you need.
<?php
$t = date("H");
if ($t < "10") {
echo "Have a good morning!";
} elseif ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>
The ternary operator provides a way to write a simple if-else statement on a single line. It uses the ? : syntax.
<?php
$age = 20;
$status = ($age >= 18) ? "Adult" : "Minor";
echo $status; // Outputs: Adult
?>
if ($condition): and endif;. This makes it easier to track opening and closing brackets in large templates.
{ } even for single lines of code. It prevents bugs when you later decide to add a second line to that block.