Conditions and loops

if / elseif, the match expression, foreach, for and while.

Runs in Zerethon IDE · PHP 8.4 Official PHP documentation ↗
main.php
<?php

for ($n = 1; $n <= 4; $n++) {
    if ($n % 2 === 0) {
        echo "$n even\n";
    } elseif ($n === 3) {
        echo "$n three\n";
    } else {
        echo "$n odd\n";
    }
}

foreach (['SAT', 'MON'] as $day) {
    $kind = match ($day) {
        'SAT', 'SUN' => 'weekend',
        default => 'weekday',
    };
    echo "$day is a $kind\n";
}

foreach (['ada' => 90, 'alan' => 85] as $name => $score) {
    echo "$name: $score\n";
}

$i = 0;
while (++$i <= 2) {
    echo "i = $i\n";
}

Output

1 odd
2 even
3 three
4 even
SAT is a weekend
MON is a weekday
ada: 90
alan: 85
i = 1
i = 2

Tip: match compares with ===, returns a value and needs no break; an unmatched value throws UnhandledMatchError.

Related topics

Official references