Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

PHP
PHP
0/12 completed
Beginner
Hello PHPVariables and arraysControl flowFunctions
Intermediate
Strings, dates and JSONForms, requests and sessionsDatabases with PDO
Advanced
Object-oriented PHPErrors, exceptions and typesSecurity essentials
Pro
Composer, autoloading and testingLaravel basics
Tracks / PHP / Beginner

Control flow

PHP's if, loops and switch look like C and JavaScript, with two modern additions you'll use a lot: the match expression and the null-safe operator. This lesson covers all of them.

if, elseif, else

PHP · editable

Conditions go in parentheses, and blocks use braces. Logical operators: &&, ||, ! (there are also and/or, with confusing precedence, so stick to the symbols).

Comparing

PHP · editable

in_array($value, $list, true) with the third argument true uses strict comparison, which is usually what you want.

match: the modern switch

match compares one value with strict comparison, returns a value, and throws an error if nothing matches:

PHP · editable
PHP · editable

An unmatched match throws UnhandledMatchError, so a forgotten case shows up immediately instead of silently doing nothing.

switch

switch is the older form. It compares loosely (==) and falls through without break:

PHP · editable

Prefer match in new code: it's shorter, stricter and can't fall through by accident.

Loops

PHP · editable

break, continue and modifying in foreach

PHP · editable

⚠️ After foreach ($items as &$item), $item still points at the last element. Forgetting unset($item) causes a famous bug where a later loop overwrites it.

Null-safe access

?-> calls a method or reads a property only if the object isn't null:

PHP · editable

Together with ??, it replaces deep chains of if ($x !== null && $x->y !== null …).

FizzBuzz with match

PHP · editable

Practice

  1. Use match to convert a number 1–7 into a day name, with a default for anything else.
  2. Print the multiplication table of 7 with a for loop.
  3. Loop over ["apple" => 3, "banana" => 0, "cherry" => 7], skipping out-of-stock items with continue.
  4. Read a number with readline() (type it in the Input box) and say whether it's prime.
✎ Check your understanding

1.What does match do when no arm matches and there's no default?

2.How does match compare values?

3.What does $order?->customer?->name return when $order is null?

4.What should you do after foreach ($items as &$item)?

← Variables and arrays