Guard Clauses and Early Returns

5.Guard Clauses and Early Returns

M

In this chapter

We'll learn how to take a deeply nested function apart: guard clauses that return early, continue as a guard inside loops, how to flip a condition correctly, when a conditional expression beats an if, and a short list of control-flow design rules that keep code flat and readable.

14–16 min

The Problem in Real Life

Back to the function that started it all: freeSlots(). It works out the free slots for a day, using the closing hour, the lunch break, the bookings that are already made and the time right now. It's correct now — Sunday returns nothing — but Mia still can't read it.

She counts. The line that actually adds a free slot sits under an if, inside an if, inside an if, inside a for, inside another if. Every bug this week hid somewhere in a shape like this. "It looks like a staircase," she says.

"Programmers call it the arrow," says Marcus. "The code points right, and your attention goes with it."

M

To understand one line, I have to remember five conditions above it.

Mia

The Staircase vs. Flat Code

Too many levels

Each if adds a level. By the fifth, nobody can tell which condition a line depends on.

The important line is hidden

The one line that does the real work sits at the far right, under every check.

The checks are really filters

Closed day, lunch break, already booked, already past: each one just means "skip this".

Guard Clauses and Early Returns

Same result, different shape: you now know every control-flow statement. This last chapter is about combining them well. The same logic can be written so it's hard to read or easy to read, and PHP doesn't care which. People do, because people find the bugs. These are the tools:

  • Guard clauses: handle the cases where the function can't do its job first, and return early.
  • continue as a guard: inside a loop, skip the items you don't want at the top of the block.
  • Named conditions: give a complicated condition a name, like $isLunchBreak.
  • Conditional expressions: when you only choose a value, use ? :, ?? or match instead of if/else.

The staircase: here's freeSlots() as it was. Every condition opens a new level, and the line that does the real work — $free[] = ... — sits inside all of them. To check that line, you have to hold every condition above it in your head, and the closing braces at the bottom no longer tell you which if they belong to. Nothing in it is wrong. It's just hard to read, and code that's hard to read is where bugs hide. It uses in_array($m, $booked, true) from chapter 2, and implode(" ", ...), which joins an array into one string with spaces between the items (Act 08).

Before: the staircase
<?php
function freeSlots(string $day, array $booked, int $now): array
{
$free = [];
$closing = match ($day) {
"Saturday" => 16 * 60,
"Sunday" => null,
default => 18 * 60,
};
if ($closing !== null) {
for ($m = 9 * 60; $m < $closing; $m += 30) {
if ($m < 13 * 60 || $m >= 14 * 60) {
if (!in_array($m, $booked, true)) {
if ($m > $now) {
$free[] = sprintf("%d:%02d", intdiv($m, 60), $m % 60);
}
}
}
}
}
return $free;
}
// Saturday, 9:30 and 10:00 already booked, the time now is 9:00
echo implode(" ", freeSlots("Saturday", [570, 600], 9 * 60)), "\n";
// 10:30 11:00 11:30 12:00 12:30 14:00 14:30 15:00 15:30

Guard clauses and early returns: look at the outermost if: if ($closing !== null) wraps the whole rest of the function. Flip it around: if the shop is closed, return [] straight away. That one line is a guard clause. It guards the rest of the function by leaving early in the case where there's nothing to do. After it, the function knows the shop is open, and the main work moves one level to the left. Put guard clauses at the top of a function, one per "I can't continue" case. Returning early like this is called an early return. Some older style guides wanted one return per function; for guard clauses at the top, modern PHP code doesn't follow that rule.

continue is a guard clause for loops: inside the for loop, the three nested checks — not in the lunch break, not booked, not in the past — all mean "keep this slot". Flip each one into "skip this slot" and continue. Now each check is one short, flat if, and the line that adds the slot sits at the bottom of the loop, at the same level as the checks. The diagram and the code below show the flat version. Its output is the same as the staircase's.

The flat freeSlots(): guards first, happy path at the bottom

Is the shop closed all day?

yes → return [] (guard clause)

no

for each slot from 9:00 to closing

the loop

each slot

Lunch break? Already booked? Already past?

any yes → continue (skip this slot)

all no

$free[] = the slot

the happy path, at the left edge

After: guard clauses and continue
<?php
function freeSlots(string $day, array $booked, int $now): array
{
$closing = match ($day) {
"Saturday" => 16 * 60,
"Sunday" => null,
default => 18 * 60,
};
if ($closing === null) {
return []; // guard: closed all day
}
$free = [];
for ($m = 9 * 60; $m < $closing; $m += 30) {
$isLunchBreak = $m >= 13 * 60 && $m < 14 * 60;
if ($isLunchBreak) {
continue;
}
if (in_array($m, $booked, true)) {
continue; // already booked
}
if ($m <= $now) {
continue; // already in the past
}
$free[] = sprintf("%d:%02d", intdiv($m, 60), $m % 60);
}
return $free;
}
echo implode(" ", freeSlots("Saturday", [570, 600], 9 * 60)), "\n";
// 10:30 11:00 11:30 12:00 12:30 14:00 14:30 15:00 15:30 — the same result
echo count(freeSlots("Sunday", [], 0)), " slots on Sunday\n";
// 0 slots on Sunday

Flipping a condition correctly: when you turn "keep it if" into "skip it if", you need the opposite condition, and that's easy to get wrong. The staircase kept slots where $m < 13 * 60 || $m >= 14 * 60 (before 13:00 or from 14:00). The opposite isn't the same thing with ! in front of each part, still joined by ||. The rule, called De Morgan's law: !($a || $b) is !$a && !$b, and !($a && $b) is !$a || !$b. Flip each part and swap && with ||. So the opposite is $m >= 13 * 60 && $m < 14 * 60: from 13:00 and before 14:00. That's the lunch break, so name it: $isLunchBreak. A named condition can't be misread.

Flipping a condition with De Morgan's law
<?php
$m = 13 * 60 + 30; // 13:30, in the lunch break
$keep = $m < 13 * 60 || $m >= 14 * 60; // before 13:00 OR from 14:00
$skip = $m >= 13 * 60 && $m < 14 * 60; // flip each part AND swap || for &&
var_dump($keep); // bool(false)
var_dump($skip); // bool(true)
var_dump($skip === !$keep); // bool(true): always the exact opposite

Conditional expressions: an if/else whose only job is to put one of two values into a variable is really choosing a value. Write it as an expression: $label = $freeSlots > 0 ? "Book now" : "Fully booked"; (the ternary from Act 05). Use ?? for "this value, or a default when it's null", and match for more than two choices (chapter 3). Use if statements for actions, such as saving, sending or printing, and expressions for values.

Choosing a value: an expression instead of if/else
<?php
$freeSlots = 0;
// An if/else that only picks a value...
if ($freeSlots > 0) {
$label = "Book now";
} else {
$label = "Fully booked";
}
// ...reads better as one expression
$label = $freeSlots > 0 ? "Book now" : "Fully booked";
echo $label, "\n";
// Fully booked

Control-flow design: a few rules keep code flat. Handle the special cases first and leave early. Keep the normal case — the happy path — at the left edge. Inside loops, skip with continue instead of wrapping the body in an if. Give long conditions names. Choose values with expressions. And when a function still has too many levels, split it into smaller functions (Act 09). Two levels of nesting inside a function is comfortable; four is a warning sign. The table below lists the common problems and what to do instead.

Table — Control-flow problems and what to do instead
ProblemWhat to do instead
An if inside an if inside an ifReturn early with guard clauses; join simple conditions with &&
One big if around the whole functionFlip the condition and return early
One big if around the whole loop bodyFlip the condition and continue
An if/else that only sets one variableOne expression: ?:, ?? or match
A condition you have to read twiceGive it a name, like $isLunchBreak
Still too many levelsSplit the work into smaller functions (Act 09)

Key Takeaway

Deep nesting hides the important line under every condition. Flatten it: guard clauses handle the "can't continue" cases first and return early, continue does the same inside loops, and the happy path stays at the left edge. When you flip a condition, flip each part and swap && with || (De Morgan). Name long conditions, choose values with expressions (?:, ??, match), and keep if for actions.

Why This Matters

Flat code isn't about looks. Every condition a reader has to remember is a chance to miss one, and the Sunday bug hid for weeks in code nobody could read. With guards at the top and the happy path at the left edge, each rule is one short line you can check on its own.

These habits — return early, skip early, name your conditions — carry through the rest of the course: into functions (Act 09), validation (Act 14) and the Laravel code in the next courses.

freeSlots() is flat now: one guard for closed days, three continue checks, and the line that adds a slot at the bottom. Olivia sends Grace a free haircut voucher — for a Saturday. One job is left: Olivia wants the whole week on one page, with the lunch break and the closed Sunday. That's the checkpoint.