PHP if, switch and loops

Beginner  Nov 3, 2026

Make decisions and repeat work with if, switch, for, foreach and while.

PHP if, switch and loops
The steps of this tutorial at a glance.
The steps of this tutorial at a glance.

if / elseif / else

<?php
$score = 72;
if ($score >= 90) {
    echo 'A';
} elseif ($score >= 60) {
    echo 'Pass';
} else {
    echo 'Fail';
}
How the code in this section fits into the page.
How the code in this section fits into the page.

Compare carefully

Use === (same value and same type) instead of ==. It avoids surprises like '0' == false.

switch

switch ($day) {
    case 'sat':
    case 'sun':
        echo 'Weekend';
        break;
    default:
        echo 'Weekday';
}

Loops

for ($i = 1; $i <= 3; $i++) { echo $i; }          // 123

$fruits = ['apple', 'mango'];
foreach ($fruits as $f) { echo $f, ' '; }

$n = 3;
while ($n > 0) { echo $n--; }                      // 321

Tips

  • foreach is the loop you will use most, for arrays and database rows.
  • Use break to leave a loop early and continue to skip to the next round.
  • Always make sure a while loop can end, otherwise the page hangs.
The main points of this section.
The main points of this section.

More tutorials