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.
= instead of ==/===. if ($active = true) assigns instead of comparing, and the block always runs regardless of the real condition.
{}, only the single next statement is conditional — adding a second line later without braces runs it unconditionally by mistake.
elseif, or use match (PHP 8+) for clean value-based branching.
A second example — computing a discount tier with an elseif chain:
<?php
$orderTotal = 850;
if ($orderTotal >= 1000) {
$discount = "15%";
} elseif ($orderTotal >= 500) {
$discount = "10%";
} else {
$discount = "0%";
}
echo "Discount: $discount"; // Discount: 10%
?>
Q: Can I use if without curly braces for one line?
A: Yes, PHP allows it, but it's risky the moment someone adds a second line later without noticing the missing braces — always use {}.
Q: What's the difference between elseif and else if?
A: In PHP they behave identically — elseif (one word) is just the conventional style, though else if (two words) also works.
Q: When should I use a switch instead of if/elseif?
A: When you're comparing one variable against many exact values — a switch (or match in PHP 8+) reads more cleanly than a long elseif chain. See the PHP manual's if reference for the alternative syntax too.