An if statement is a control structure used to make decisions in your code.
It evaluates a specific condition and decides whether or not to run a block of logic. If the condition is true, the code executes; if it is false, the code is skipped entirely.
To write an if statement, use the if keyword followed by a condition wrapped in parentheses (). The code you want to execute if that condition is met lives inside curly braces { ... }.
<?php
$price = 20;
$discount = 10;
if ($price > $discount) {
echo "The price is greater than the discount!";
}
As your logic grows more complex, you can chain multiple decisions together to handle alternative paths.
elseif Provides an additional condition to check only if the previous conditions were false. You can use as many elseif blocks as you need.
else Acts as the ultimate fallback block. It requires no condition and runs only if none of the prior conditions were true.
Implementation Example In standard application logic, the control structure reads sequentially from top to bottom, executing the very first block that matches a true condition:
<?php
$role = "Editor";
if ($role == "Admin") {
echo "Welcome to the administrator dashboard.";
} elseif ($role == "Editor") {
echo "Welcome! You can edit articles.";
} else {
echo "Welcome, regular user.";
}
How the Logic Flows: PHP checks the first condition ($role == "Admin"). This is false, so it skips the first echo.
It moves down to the elseif condition ($role == "Editor"). This is true, so it executes the code inside this block.
Because a match was found, PHP skips the rest of the structure (including the else block) and continues running any code written below it.