Coding/Learn/php/php control flow and match
PHP Foundational Course
01.Introduction, Server-Side Architecture & Syntax
02.Variables, Strict Types & Dynamic Casting
03.Strings, Numbers & Built-in Math Functions
04.Operators, Null Coalescing & Magic Constants
05.Control Flow: If-Else, Switch & Modern Match Expressions
06.Loops: While, For & Foreach Traversal
07.Functions, Type Declarations & Named Arguments
08.Arrays & Functional Array Manipulation
09.Superglobals, Form Handling & Input Sanitization
10.Date, Time & DateTimeImmutable Objects
11.File System, Streams & I/O Operations
12.Cookies, Sessions & State Management
13.Exceptions, Throwables & Custom Error Fences
14.Classes, Objects & Constructor Property Promotion
15.Inheritance, Access Modifiers & Method Overriding
16.Interfaces, Abstract Classes & Polymorphism
17.Traits, Static Members & Namespaces
18.PDO, MySQL & Prepared Statements against SQL Injection
19.JSON & XML REST API Interoperability
20.Capstone: Production Secure Backend API & User Registry Engine
Course Certificate0%

Complete all lessons to earn

LearnControl Flow: If-Else, Switch & Modern Match Expressions
5 / 20 0%
Lesson 05 of 20
9 mins read

Control Flow: If-Else, Switch & Modern Match Expressions

PreviousNext Lesson
In Plain English

Branch execution based on dynamic conditions. Learn if...elseif...else structures, switch statements, and the modern PHP 8 match expression which provides strict type comparison (===) and returns a value directly.

The Mental Model

"A switch statement is like a multi-way train switch that requires manual stop signals (break) at every junction. A match expression is a smart rotary dial that clicks cleanly into one exact matching slot and instantly outputs the result."

Deep Dive: How It Works

If-Else Hierarchy: Evaluates boolean conditions sequentially from top to bottom.

Switch Statements: Uses loose comparison (==) and falls through branches without explicit break;.

PHP 8 match Expression: Evaluates strictly (===), produces a return value, executes only the matched arm, and does not require break.

Syntax Blueprint

<?php

$status = match ($statusCode) {
    200 => "OK",
    404 => "Not Found",
    default => "Unknown",
};

The match expression maps input expressions to return values with strict comparison.

PointCore Rules to Remember

Point star
Match Expression Benefits: Stricter, safer, and cleaner than switch; throws UnhandledMatchError if no arm matches and default is missing.
Point star
Ternary Expressions: $status = $isOnline ? "Active" : "Offline"; provides concise inline checks.
Point star
Multiple Match Arms: Combine multiple cases into one arm: 200, 201, 204 => "Success",

Common Beginner Traps & How to Fix Them

Mistake:Forgetting break; in traditional switch cases, causing fall-through bugs.

Why it happens: switch statements execute subsequent cases automatically unless explicitly terminated with break.

How to fix: Use PHP 8 match expressions or always include break; in switch branches.

Pro Tip: Prefer match over switch in modern PHP for mapping enum values, HTTP status codes, and user roles.

Live Interactive Example

Hit Run Code to see it live
HTTP Status Code Mapping with Match Expression
PHP 8.2 / CLI
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Output Console
Click "Run Code" to view the rendered output.
How it works: match strictly matched 200 and assigned the corresponding string directly.

Your Turn: Micro Challenge

No pressure! Edit the starter code below and test your solution with instant feedback.

Micro Exercise

Map User Roles with Match

  • PointDeclare $role = "admin".
  • PointUse a match ($role) expression to return "Full Access" for "admin", "Read Only" for "guest", and "Restricted" for default.
  • PointStore result in $permission and print "Permission: [permission]".
1
2
3
4
5
6
Sandbox Output
Click "Run & Check" to test your solution.

Finished reading and practicing?

Mark this lesson as completed to update your course progress.

PreviousNext Lesson
Overview100 SheetLearnCertificates