Control Flow & FunctionsCore· 35 min read

Conditions: if, else & switch

Make decisions in PHP with if, else, elseif and switch — run different code depending on conditions, the foundation of every dynamic page.

What you will learn

  • Branch with if / elseif / else
  • Use switch
  • Combine conditions

if / elseif / else

An if statement runs a block of code only when a condition is true. elseif offers another condition to try if the first was false, and else is the fallback that runs when nothing above matched. PHP checks the conditions from top to bottom and stops at the first one that is true.

if / elseif / else
<?php
  $marks = 72;
  if ($marks >= 75) {
    echo "Grade A";
  } elseif ($marks >= 50) {
    echo "Grade B";
  } else {
    echo "Fail";
  }
?>

Step by step with $marks set to 72: PHP first asks "is 72 ≥ 75?" — no, so it skips Grade A. Next it asks "is 72 ≥ 50?" — yes, so it prints Grade B and stops without ever reaching else. The braces { } mark where each block begins and ends.

Note: Output (in the browser): Grade B Only one branch ever runs — the first condition that is true. If $marks were 40, both checks would fail and the else would print Fail.

switch

When you are comparing one variable against many fixed values, a switch is tidier than a long chain of elseif. It checks each case in turn; break stops it once a match is found, and default runs if nothing matched.

switch with break
<?php
  $day = "Mon";
  switch ($day) {
    case "Mon": echo "Monday"; break;
    case "Tue": echo "Tuesday"; break;
    default: echo "Another day";
  }
?>

Here $day is "Mon", so PHP jumps to case "Mon", prints Monday, and the break exits the switch. If $day had been "Sun", no case would match and default would print Another day.

Note: Output (in the browser): Monday The break is important — without it, PHP would "fall through" and keep running the next cases too. Always end each case with break unless you really want that.

Q. In PHP, "else if" is written as one word:

Answer: PHP uses elseif (one word) for chained conditions (else if with a space also works).

✍️ Practice

  1. Build a grade calculator with if/elseif/else.
  2. Use switch to turn a number 1–3 into a name.

🏠 Homework

  1. Write a script that says “Good morning/afternoon/evening” based on an hour variable.
Want to learn this with a mentor?

CodingClave runs guided, project-based training (28-day, 45-day & 6-month batches).

Explore Training →