PHP for the Web·PHP from first script to a working app

Control flow and loops

Branch with if and match, then loop with for, while and foreach.

Beginner 13 min read Lesson 2 of 300 Challenge included
What you will be able to do
  • Use if/elseif/else for general conditions.
  • Use match when mapping one value to one result.
  • Prefer foreach for arrays.
  • Break out of loops deliberately and avoid deeply nested branches.

In plain English

Most PHP is data shaping: decide what to show, then iterate over rows. match is a strict comparison expression and returns a value, which makes it cleaner than a long if chain for mapping states to labels.

flow.phpPHP
<?php
$status = 'published';

$label = match ($status) {
    'draft' => 'Draft',
    'published' => 'Live',
    default => 'Unknown',
};

foreach (['HTML', 'CSS', 'PHP'] as $index => $course) {
    echo ($index + 1) . ". {$course}\n";
}
Your turn

Map a score to a grade

Easy

Write a match expression that returns A for 90 and above, B for 80 and above, and C otherwise.

PHP · starter
$score = 84;
Check your understanding before moving on.
Knowledge checkQuestion 1

How does match compare values?

Select an answer to continue
Study tools

Make it yours.

Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.

Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Next: Functions and scope
Lesson 2 of 300 · 0% of course