if, elseif, else
<?php
$marks = 72;
if ($marks >= 75) {
echo "Distinction";
} elseif ($marks >= 40) {
echo "Pass";
} else {
echo "Fail";
}switch and match
$day = "Sat";
switch ($day) {
case "Sat":
case "Sun":
echo "Weekend";
break;
default:
echo "Weekday";
}
echo match(true) {
$marks >= 75 => "A",
$marks >= 60 => "B",
default => "C",
};match (PHP 8) is stricter and returns a value.
Loops
for ($i = 1; $i <= 5; $i++) {
echo "Number $i<br>";
}
$n = 3;
while ($n > 0) {
echo $n--;
}
$subjects = ["Maths", "Science", "English"];
foreach ($subjects as $index => $subject) {
echo ($index + 1) . ". $subject<br>";
}break and continue
for ($i = 1; $i <= 10; $i++) {
if ($i % 2 === 0) continue; // skip even numbers
if ($i > 7) break; // stop
echo $i;
}Alternative syntax in HTML templates
<?php if ($loggedIn): ?>
<p>Welcome back!</p>
<?php else: ?>
<p>Please log in.</p>
<?php endif; ?>Practice
Print a multiplication table for a number of your choice and list all numbers from 1 to 100 divisible by 7.