Lesson 6 of 12

PHP Conditions: if, else and match

A program becomes useful when it can react differently to different situations: show a login link to guests and a profile link to members, or charge delivery only on small orders. These decisions are written with conditional statements. This lesson covers PHP conditions from the simple if to the modern match expression. You will use the comparison and logical operators from the previous lesson to build the conditions.

The if statement

if runs a block of code only when its condition is true. The condition goes in round brackets and the code in curly braces:

if ($stock === 0) { echo "Out of stock"; }

Add else for the code that should run when the condition is false, and elseif to test further conditions in order. PHP checks each condition from top to bottom and runs only the first block whose condition is true; the rest are skipped.

<?php
$marks = 78;

if ($marks >= 90) {
    $grade = "A+";
} elseif ($marks >= 75) {
    $grade = "A";
} elseif ($marks >= 60) {
    $grade = "B";
} elseif ($marks >= 40) {
    $grade = "C";
} else {
    $grade = "Fail";
}

echo "Marks: $marks, Grade: $grade\n";

$attendance = 82;
if ($marks >= 40 && $attendance >= 75) {
    echo "Eligible for the certificate";
} else {
    echo "Not eligible yet";
}
Output
Marks: 78, Grade: A
Eligible for the certificate

Order matters. If the >= 40 check came first, a student with 95 marks would get a C, because PHP stops at the first true condition. Always arrange ranges from the most specific to the most general.

Tip: Always use curly braces, even for a one-line block. PHP allows you to leave them out, but adding a second line later without noticing the missing braces is a common bug.

Combining and nesting PHP conditions

Use && when every condition must be true and || when any one is enough, as in the certificate check above. You can also place an if inside another if, but deep nesting quickly becomes hard to read. A useful pattern is the early return or guard clause: deal with the error cases first, then write the main logic without extra indentation. You will see this in the functions and forms lessons.

Be explicit about empty values

You can write if ($name) { ... }, and PHP will convert $name to a boolean using the truthy rules from PHP Data Types. That is short, but it treats "0", 0 and an empty string the same way, which is not always what you mean. A quantity of 0 is a real answer, not a missing one. Prefer conditions that say exactly what you are checking: $name !== '' for an empty string, $qty === null for a missing value, or count($items) > 0 for an empty list. Your intent is then clear to anyone reading the code.

The match expression (PHP 8)

When you compare one value against a list of possible values, a long elseif chain becomes repetitive. PHP 8 introduced match for exactly this job:

<?php
$orderStatus = "shipped";

$message = match ($orderStatus) {
    "pending"             => "We have received your order.",
    "packed", "shipped"   => "Your order is on its way.",
    "delivered"           => "Delivered. Enjoy!",
    "cancelled"           => "This order was cancelled.",
    default               => "Unknown status.",
};

echo $message, "\n";

$hour = 15;
$greeting = match (true) {
    $hour < 12 => "Good morning",
    $hour < 17 => "Good afternoon",
    default    => "Good evening",
};
echo "$greeting, Selvi!";
Output
Your order is on its way.
Good afternoon, Selvi!

Why is match often better than the older switch statement?

  • It is an expression: it returns a value, so you can assign the result directly to a variable.
  • It compares with strict equality (===). switch uses loose ==, which can match values you did not expect.
  • There is no break to forget. Each arm runs only its own expression, so there is no accidental “fall-through”.
  • If no arm matches and there is no default, PHP throws an UnhandledMatchError instead of silently doing nothing, so missing cases are found early.

Several values can share one arm by separating them with commas, as with "packed", "shipped". The match (true) pattern in the second half of the example checks ranges: the first arm whose condition is true wins.

Watch out: Each match arm holds a single expression, not a block of statements. If a case needs several lines of work, use if/elseif, or call a function from the arm.

What about switch?

You will still see switch in older code, so it is worth recognising. Each case must end with break, or PHP carries on into the next case. For new code, match is usually the clearer choice.

Conditions inside HTML templates

When PHP is mixed with HTML, curly braces spread across several <?php ?> tags are hard to follow. PHP offers an alternative syntax that replaces the opening brace with a colon and the closing brace with endif;:

<?php $cartCount = 0; ?>
<nav>
<?php if ($cartCount > 0): ?>
  <a href="/cart">Cart (<?= $cartCount ?>)</a>
<?php else: ?>
  <span>Your cart is empty</span>
<?php endif; ?>
</nav>
Output
<nav>
  <span>Your cart is empty</span>
</nav>

This style of writing PHP conditions is common in WordPress themes and other templates. The same idea works for loops with foreach: and endforeach;, which you will meet in PHP Loops.

Further reading

Key takeaways

  • if, elseif and else run only the first block whose condition is true.
  • Order range checks from most specific to most general, and always use curly braces.
  • match returns a value, uses strict comparison and has no fall-through.
  • An unmatched value without default throws UnhandledMatchError.
  • In HTML templates, the alternative syntax if: … else: … endif; keeps markup readable.

Quick quiz

Check what you learned – pick an answer.

1. With $marks = 95, which grade does this print? if ($marks >= 40) { echo "C"; } elseif ($marks >= 90) { echo "A+"; }

2. Which comparison does match use?

3. What happens if a match expression has no matching arm and no default?

Practice exercise

Given $day = "Sunday";, use a match expression to print the opening hours of a café: Monday to Friday "8 am – 9 pm", Saturday "9 am – 10 pm", Sunday "Closed". Any other value should print "Invalid day".

Show a hint

List the five weekdays in one arm separated by commas.

Show the solution
<?php
$day = "Sunday";

$hours = match ($day) {
    "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" => "8 am – 9 pm",
    "Saturday" => "9 am – 10 pm",
    "Sunday"   => "Closed",
    default    => "Invalid day",
};

echo $hours; // Closed

Progress is saved in this browser only.