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
Conditions go in parentheses, and blocks use braces. Logical operators: &&, ||, ! (there are also and/or, with confusing precedence, so stick to the symbols).
Comparing
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:
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:
Prefer match in new code: it's shorter, stricter and can't fall through by accident.
Loops
break, continue and modifying in foreach
⚠️ After
foreach ($items as &$item),$itemstill points at the last element. Forgettingunset($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:
Together with ??, it replaces deep chains of if ($x !== null && $x->y !== null …).
FizzBuzz with match
Practice
- Use
matchto convert a number 1–7 into a day name, with a default for anything else. - Print the multiplication table of 7 with a
forloop. - Loop over
["apple" => 3, "banana" => 0, "cherry" => 7], skipping out-of-stock items withcontinue. - Read a number with
readline()(type it in the Input box) and say whether it's prime.
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)?