PHP 8 Basics · 8 min read · Beginner
Control Flow, match() & foreach Loops
Branch cleanly with PHP 8 match expressions and iterate over lists and key-value arrays using foreach.
What you'll learn
- Replace verbose switch blocks with PHP 8's strict match() expression
- Iterate values and key-value pairs cleanly with foreach
PHP 8 introduced match, a safer, stricter, and shorter upgrade to switch. It uses strict === comparisons, needs no break statements, and returns a value directly!
$badge = match ($track) {
'HTML', 'CSS' => 'Frontend Core',
'SQL', 'PHP' => 'Backend Stack',
default => 'General Track',
};
Fill-in-the-Blank Exercise
Modern PHP 8 match() & foreach
Use match() to map a role and foreach to iterate over $items.
$label = ($role) {
'admin' => 'Administrator',
default => 'Learner',
};
($items as $item) {
echo $item;
}Try It Yourself
PHPPHP 8 match() & foreach Loop
PHP 8 Output (WebAssembly)
Click Run PHP to execute real PHP 8 right in your browser.
Check Your Understanding
Score: 0 / 1
1. How does PHP 8's match expression compare values?
Study Workspace
Finished this lesson?
Your progress is saved locally in your browser, no account needed.