Control Flow

View saved

If and else

Conditions do not need parentheses around the whole statement beyond the usual form.

<?php
$score = 82;
if ($score >= 70) {
  echo "passed\n";
} else {
  echo "retry\n";
}

elseif chains

Test several cases in order.

if ($score >= 90) {
  echo "excellent\n";
} elseif ($score >= 70) {
  echo "ok\n";
} else {
  echo "practice\n";
}

Loops

for, while, and foreach cover most needs.

for ($i = 1; $i <= 3; $i++) {
  echo $i, "\n";
}

Switch

Cases should break unless fall-through is intentional.

switch ($score) {
  case 100:
    echo "perfect\n";
    break;
  default:
    echo "keep going\n";
}

Comments

One comment per signed-in account. Comments are saved with this page’s URL.