Learn PHP from Scratch

PHP Conditions and Loops

Lesson 3 of 7 2 min read Updated 10 October 2026

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.

Practice tasks

Reading is not enough. Try these without copying code, then compare with the lesson.

  • Write if/elseif/else for marks and grades.
  • Loop through 1 to 10 with for and foreach.
  • Use switch for a menu choice.

Common mistakes

  • Putting = inside an if where == or === was meant.
  • Forgetting to end a statement with a semicolon.

Quick check

What does foreach do?

Loops over every item of an array.

When do you need break in a switch?

To stop execution from falling through to the next case.