Make your scripts react with if and match, then repeat actions with for, foreach, and while.
Open this lesson in KodokonA condition lets the script choose a path: “if this is true, do that, otherwise do something else”. The if keyword tests an expression that evaluates to true or false, using the comparison operators: > (greater than), < (less than), >=, <=, === (equal, same value AND same type) and !== (different). elseif adds another test if the previous one failed, and else runs when no test succeeded. Tests are read from top to bottom: the first one that is true wins.
<?php
$temperature = 12;
if ($temperature > 25) {
echo "It's hot.";
} elseif ($temperature > 15) {
echo "It's mild.";
} else {
echo "Grab a jacket!";
}When you compare the same variable against several specific values, the match expression is more elegant. It compares the variable to each case (strict comparison, value and type) and returns a value directly, which you can store in a variable. The default case acts as a safety net when no value matches.
<?php
$day = "saturday";
$message = match ($day) {
"saturday", "sunday" => "It's the weekend!",
"monday" => "Hang in there, back to work.",
default => "Have a good weekday.",
};
echo $message;A loop repeats a block of instructions several times, without copy-pasting the code. The for loop is ideal when you know the number of rounds ahead of time. It reads in three parts, separated by semicolons: the start ($i = 1), the continuation condition ($i <= 5, it keeps going as long as this is true) and the step ($i++, which adds 1 to $i on each round).
<?php
for ($i = 1; $i <= 5; $i++) {
echo "Round number {$i}<br>";
}Two other loops round out the toolkit. foreach walks through an array (a list of values, covered in the next lesson) and hands you each element one after another. while repeats its block as long as its condition stays true: it's up to you to change the situation inside the loop so it eventually stops.
<?php
$fruits = ["apple", "pear", "kiwi"];
foreach ($fruits as $fruit) {
echo "Fruit: {$fruit}<br>";
}
$countdown = 3;
while ($countdown > 0) {
echo "{$countdown}...<br>";
$countdown--;
}
echo "Go!";else block run?match apart from if?while condition stays true forever?