Web pages often need to change depending on the situation. Show "Log in" to visitors but "My account" to members. Show a "Sold out" label when stock is zero. Greet people with "Good morning" or "Good evening" depending on the time. In PHP, that's the job of conditions.
An if statement checks whether something is true and runs a block of code only if it is. You can add elseif branches and a final else. PHP 8 also has match, a neat way to pick a value from a list of options.
In this lesson you'll learn PHP's comparison operators, including the important difference between == and ===, and write if/elseif/else chains and match expressions.
Comparison operators
| Operator | Meaning | Example |
|---|---|---|
== | equal value | $qty == 0 |
=== | equal value and same type | $id === 5 |
!= / !== | not equal / not identical | $role !== "admin" |
> < >= <= | greater / less (or equal) | $age >= 18 |
== converts types before comparing, so "5" == 5 is true. === also checks the type, so "5" === 5 is false. Prefer === unless you specifically want type conversion; it avoids surprises.
if, elseif, else
$hour = 15;
if ($hour < 12) {
echo "Good morning";
} elseif ($hour < 18) {
echo "Good afternoon";
} else {
echo "Good evening";
}- The condition goes in round brackets; the code to run goes in curly braces.
- Only the first branch whose condition is true runs.
- PHP writes
elseifas one word (else ifalso works).
Logical operators, ternary and ??
&&(and),||(or) and!(not) combine conditions, just as in JavaScript.- The ternary operator chooses between two values:
$label = $stock > 0 ? "In stock" : "Sold out"; - The null coalescing operator
??gives a fallback when a value is missing or null:
$name = $_GET["name"] ?? "guest";That line reads a name from the page address, such as ?name=Sam, or uses "guest" if there isn't one. You'll see ?? everywhere in PHP code that handles forms.
match
match compares one value against several options and returns the matching result:
$size = "M";
$price = match ($size) {
"S" => 2.50,
"M" => 3.00,
"L" => 3.50,
default => 0,
};match uses strict === comparison, needs no break, and lets you list several values for one result: "S", "XS" => 2.50. If nothing matches and there's no default, PHP throws an error, which helps you spot unexpected values.
switch, and why match is usually better
Older PHP code often uses switch to compare one value with several options:
switch ($size) {
case "S":
$price = 2.50;
break;
case "M":
$price = 3.00;
break;
default:
$price = 0;
}switch uses loose == comparison and falls through to the next case if you forget break, two common sources of bugs. match compares strictly, never falls through and returns a value directly, so prefer match in new code. switch is still useful when each case runs several statements rather than producing a value. The switch versus match lesson compares them side by side.
Comparing with the spaceship operator
The spaceship operator <=> compares two values and returns -1, 0 or 1, depending on whether the left side is smaller, equal or larger. 2 <=> 5 gives -1. It's mainly used for sorting: usort($products, fn($a, $b) => $a['price'] <=> $b['price']); sorts products from cheapest to most expensive. Comparing arrays or strings with it works too, following PHP's normal comparison rules.
PHP if else Syntax
Conditions
if ($a === $b) {
// ...
} elseif ($a > $b) {
// ...
} else {
// ...
}
$result = $condition ? "yes" : "no";
$value = $maybe ?? "fallback";
$out = match ($x) {
1, 2 => "small",
3 => "medium",
default => "large",
};PHP if else Summary
==compares values after converting types;===also compares types. Prefer===.if,elseifandelsechoose which block runs. Only one branch runs.- Combine conditions with
&&,||and!. cond ? a : bpicks a value;$x ?? "default"handles missing values.matchreturns the result for a matching value, using strict comparison.
PHP if else Examples
Each example shows the code, the output it produces and what each part does.
Stock labels
<?php
$stock = 3;
if ($stock === 0) {
echo "Sold out";
} elseif ($stock < 5) {
echo "Only $stock left!";
} else {
echo "In stock";
}Only 3 left!Line-by-line explanation
- Line 4=== checks that stock is exactly the integer 0.
- Line 63 is less than 5, so this branch runs and the else is skipped.
== versus ===
<?php
var_dump("5" == 5);
var_dump("5" === 5);
var_dump(0 == "");
var_dump(null ?? "default");bool(true)
bool(false)
bool(false)
string(7) "default"Line-by-line explanation
- Line 2== converts "5" to a number before comparing.
- Line 3=== sees a string and an int, so they're not identical.
- Line 4In PHP 8, 0 and an empty string are not equal. Older versions said true, which caused bugs.
- Line 5?? returns the fallback because the left side is null.
Prices with match
<?php
$day = "Sat";
$opening = match ($day) {
"Sat", "Sun" => "10:00 to 16:00",
"Fri" => "09:00 to 20:00",
default => "09:00 to 18:00",
};
$member = true;
$discount = $member ? 10 : 0;
echo "Open $opening, member discount $discount%";Open 10:00 to 16:00, member discount 10%Line-by-line explanation
- Lines 4 to 8match returns the text for the first matching option. Two days share one result.
- Line 11The ternary picks 10 for members.
Common PHP if else Mistakes
Using = instead of ===
if ($role = "admin") { ... }if ($role === "admin") { ... }A single = assigns "admin" to $role, and the condition is always true, so everyone becomes an admin.
Relying on loose comparison
if ($input == 0) { ... } // also true for "0" and "0.0"if ($input === 0) { ... }Forgetting default in match
$label = match ($size) { "S" => "Small", "M" => "Medium" };
// $size = "L" throws UnhandledMatchError$label = match ($size) { "S" => "Small", "M" => "Medium", default => "Other" };PHP if else in Real Projects
Conditions on PHP sites
Login checks, shipping rules, showing different menus to admins and visitors, choosing a language from the visitor's settings: almost every PHP page uses conditions. ?? is especially common when reading form fields, because a visitor might leave any field empty.
PHP if else FAQ
What is the difference between isset and empty?
isset($x) returns true when a variable exists and isn't null. empty($x) returns true when the variable is missing or holds a falsy value such as 0, "", "0", null or an empty array. Neither produces a warning for missing variables. The isset, empty and unset lesson has a full comparison table.
Did PHP 8 change how == works?
Yes. In PHP 8, comparing a number with a non-numeric string compares them as strings, so "abc" == 0 is now false; in PHP 7 it was true. Numeric strings still compare as numbers: "1" == "01" and "10" == "1e1" are both true. Using === avoids these rules entirely.
Can match test conditions instead of exact values?
Yes, with match (true). Each arm is then a condition, and the first one that is true wins: match (true) { $score >= 90 => "A", $score >= 70 => "B", default => "C" }. Order the arms carefully, just as you would an elseif chain.
What does the ?-> operator do?
It's the nullsafe operator, added in PHP 8. $user?->address?->city returns null instead of throwing an error when $user or its address is null. It's useful when reading optional data; see the null coalescing and nullsafe lesson.
Should I write elseif or else if?
Both work with curly braces, and elseif is the common PHP style. With the colon-based alternative syntax used in templates, if (...): and endif;, only elseif works, so using it everywhere keeps code consistent.
PHP if else Exercises
Answer each one and check it instantly. If you get stuck, open the hint before the answer.
Complete the code so it prints "Adult" when $age is 18 or more.
$age = 20;
($age >= 18) {
echo "Adult";
} {
echo "Minor";
}
What does this print?
$score = 72;
if ($score >= 80) {
echo "Great";
} elseif ($score >= 60) {
echo "Good";
} else {
echo "Try again";
}
Which expression is false?
What does this print?
$user = null;
echo $user ?? "Anonymous";
What does this print?
$name = null;
echo $name ?? "Guest";
PHP if else Quiz
5 questions to check what you learned.
How does PHP write "else if" as one keyword?
- elif
- elseif
- elsif
- otherwise
What's the difference between
==and===?- None
- === also checks that the types are the same
- == is faster
- === only works with numbers
What does
matchdo when no arm matches and there's no default?- Returns null
- Returns the first arm
- Throws an error
- Returns false
Which of these values is treated as false in an if condition?
- "0"
- "false"
- " "
- [0]
What's the difference between == and === in PHP?
- There's none
- === also checks that the types are the same
- == is for strings only
- === assigns a value