Skip to content

Chapter 7 of 38

Control Flow

Design branches with if, switch, match, truthiness, and guard clauses.

30 minutes 10 quick checksBy Subha Prasad
Lesson 7 of 38Course navigation

Lesson content

Read, practise, then check your understanding

if uses PHP boolean conversion. Guard clauses validate early and keep the main path shallow. Traditional switch uses loose comparison and can fall through; PHP 8 match is strict, returns a value, and never falls through.

Practical example

<?php
function grade(int $score): string {
  if ($score < 0 || $score > 100) throw new InvalidArgumentException();
  return match (true) { $score >= 80 => 'excellent', $score >= 50 => 'pass', default => 'retry' };
}

A match without a suitable arm/default throws. Avoid relying on surprising truthiness such as string '0'; transform boundary data into explicit domain types before decision logic.

Knowledge check

Answer every question correctly to complete this chapter.

Which statement best describes if?
Which PHP term matches this description: Conditional execution based on boolean conversion.
Which statement best describes elseif?
Which PHP term matches this description: A following condition tested only after earlier conditions fail.
Which statement best describes switch?
Which PHP term matches this description: Loose-comparison multi-branch selection in traditional PHP semantics.
Which statement best describes match?
Which PHP term matches this description: A PHP 8 strict, expression-based, non-fallthrough selection.
Which statement best describes guard clause?
Which PHP term matches this description: An early exit handling invalid input.

0 of 10 checks passed

Your progress is saved on this device.

Control Flow | PHP Lesson | Subha Prasad