PHP If Else
The if...else statement lets a PHP script choose which block of code to run based on whether a condition is true or false.
Making decisions with if
Programs rarely run the same way every time. Conditional statements let your code react to different inputs by running one section only when a certain test passes. In PHP the simplest form is the if statement: you give it a condition inside parentheses, and if that condition evaluates to true, the block of code inside the curly braces runs. If the condition is false, PHP skips the block entirely and moves on.
A basic if statement
<?php
$temperature = 32;
if ($temperature > 30) {
echo "It is a hot day, stay hydrated.";
}
?>The else and elseif branches
An if statement can be extended so that alternative code runs when the condition fails. The else branch provides a fallback that runs whenever the if condition is false. When you need to test several possibilities in order, elseif adds extra conditions between the first if and the final else. PHP checks each condition from top to bottom and runs the block belonging to the first one that is true, then skips the rest.
- if — runs its block when the condition is true.
- elseif — tested only if every condition above it was false; you can chain as many as you need.
- else — the catch-all that runs when none of the conditions above matched. It takes no condition of its own.
Grading with if / elseif / else
<?php
$marks = 74;
if ($marks >= 90) {
echo "Grade: A";
} elseif ($marks >= 75) {
echo "Grade: B";
} elseif ($marks >= 60) {
echo "Grade: C";
} else {
echo "Grade: F";
}
// Prints "Grade: C" because 74 is below 75 but at least 60
?>The condition is always a boolean
Whatever you write between the parentheses is converted to true or false. Comparison and logical operators produce booleans directly, but PHP also treats certain plain values as false, known as falsy values. Knowing these prevents subtle bugs where an empty string or a zero unexpectedly skips a block.
Combining conditions
<?php
$isLoggedIn = true;
$role = "editor";
if ($isLoggedIn && $role === "admin") {
echo "Full access granted.";
} elseif ($isLoggedIn) {
echo "Welcome back, limited access.";
} else {
echo "Please log in to continue.";
}
?>Exercise: PHP If...Else
Which of these string values is falsy in an if condition?