Lab 04: Control Flow

Objective

Master PHP control flow: if/elseif/else, match expressions, switch, for/while/foreach/do-while loops, break/continue, and list comprehension patterns.

Background

PHP control flow is similar to most C-style languages but with PHP-specific additions: the match expression (PHP 8.0), the null coalescing operator ??, and the nullsafe operator ?->. These modern features make PHP code concise and safe.

Time

30 minutes

Prerequisites

  • Lab 03 (Arrays)

Tools

  • PHP 8.3 CLI

  • Docker image: zchencow/innozverse-php:latest


Lab Instructions

Step 1: If / Elseif / Else

💡 ?? (null coalescing) returns the left side if it exists and is not null, otherwise the right side. It's safer than isset($x) ? $x : $default. ??= assigns the default only if the variable is null/unset — perfect for lazy initialization.

📸 Verified Output:


Step 2: Match Expression (PHP 8.0+)

💡 match vs switch: match uses strict === comparison (no type juggling), has no fallthrough, must be exhaustive (or have default), and is an expression that returns a value. switch uses loose ==, falls through by default, and is a statement. Prefer match in PHP 8+.

📸 Verified Output:


Step 3: For, While, Do-While

💡 The Collatz conjecture is an unsolved math problem — starting from any positive integer, repeatedly applying "halve if even, 3n+1 if odd" always reaches 1. Starting from 27 takes 111 steps. It's a great while loop exercise.

📸 Verified Output:


Step 4: Foreach — Arrays and Objects

💡 Always unset($reference) after a reference foreach. PHP's foreach ($arr as &$val) loop leaves $val pointing to the last element. If you later do foreach ($arr as $val), it overwrites the last element with each value — a notorious PHP bug. unset($n) breaks the reference safely.

📸 Verified Output:


Step 5: Break, Continue & Labels

💡 PHP's break N and continue N (where N is a numeric literal) control nested loops — break 2 exits both the current and outer loop. This eliminates the need for flag variables in nested search loops. N must be a positive integer literal, not a variable.

📸 Verified Output:


Step 6: Generator Functions

💡 Generators are memory-efficient — a generator that yields 1 million numbers uses O(1) memory (only the current value). A regular function returning an array of 1 million numbers uses O(n) memory. Use generators for large datasets, file processing, and infinite sequences.

📸 Verified Output:


Step 7: Exception Flow Control

💡 PHP 8 has separate Error and Exception hierarchies. DivisionByZeroError extends ArithmeticError extends Error — you can't catch it with catch (Exception $e). Use catch (Throwable $e) to catch both Error and Exception types. Always catch the most specific type first.

📸 Verified Output:


Step 8: Complete Example — Grade Calculator

💡 match(true) with range conditions is one of PHP's most readable patterns — it evaluates each arm as a boolean, stopping at the first true. Combined with chained match for GPA lookup, this replaces complex nested if-elseif chains with clean, composable functions.

📸 Verified Output:


Verification

Summary

PHP control flow is expressive and pragmatic. You've covered if/elseif/else, the modern match expression, all loop types, break N/continue N, generators, and exception flow. The match expression and null coalescing operators are among PHP 8's most impactful additions.

Further Reading

Last updated