PHPPHP

PHP: Control flow – code examples

Contents

if / elseif / else

Control flow#if#condition#elseifCompare in all languages
Use case: React differently, e.g. for grades, price tiers or permissions.
<?php
$punkte = 73;
if ($punkte >= 90) {
    echo "excellent\n";
} elseif ($punkte >= 70) {
    echo "good\n";
} else {
    echo "needs improvement\n";
}

The condition goes in parentheses, the block in curly braces. For mapping values, match is often the more elegant alternative.

for and foreach Loop

Control flow#for#foreach#loopCompare in all languages
Use case: Process every element of an array or repeat n times.
<?php
for ($i = 0; $i < 3; $i++) {
    echo "Round $i\n";
}

foreach (["Apple", "Pear"] as $frucht) {
    echo $frucht, "\n";
}

for counts with an index, foreach runs directly over the values of an array (optionally with $schluessel => $wert).

match Instead of switch

Control flow#match#switch#expression
Use case: Translate values into texts, prices or actions, e.g. HTTP status codes or roles.
<?php
$code = 404;
$text = match ($code) {
    200, 201 => "OK",
    301, 302 => "Redirect",
    404 => "Not found",
    default => "Unknown",
};
echo "$code: $text\n";

$n = 7;
echo match (true) {
    $n < 5 => "small",
    $n < 10 => "medium",
    default => "large",
}, "\n";

match is an expression, compares strictly (===) and needs no break. Without a matching branch an UnhandledMatchError occurs. match (true) replaces if/elseif chains.