R
Rishtaara
PHP Fundamentals
Lesson 7 of 32Article18 min

If, Switch & Match

Use if, else if, and else to run code only when conditions are true. Curly braces { } group multiple statements.

If...Else

Use if, else if, and else to run code only when conditions are true. Curly braces { } group multiple statements.

Real-life example: If it rains, take an umbrella. Else if it is sunny, wear a hat. Else stay inside.

if / elseif / else
<?php
$score = 82;

if ($score >= 90) {
  echo "Grade A";
} elseif ($score >= 75) {
  echo "Grade B";
} else {
  echo "Keep practicing on Rishtaara";
}
?>

Switch

switch compares one value against many cases. Use break to stop fall-through. default runs when nothing matches.

Real-life example: A switch is a vending machine keypad — press B3 for chips, B4 for cookies, default says "invalid choice."

switch statement
<?php
$day = "Mon";

switch ($day) {
  case "Mon":
    echo "Start of week";
    break;
  case "Fri":
    echo "Almost weekend";
    break;
  default:
    echo "Regular day";
}
?>

Match (PHP 8+)

match is a stricter, cleaner alternative to switch. It returns a value, uses === comparison, and throws if no arm matches (unless default is used).

Real-life example: match is a smart elevator — you pick floor 3 and it goes exactly there, no stopping at wrong floors.

match expression
<?php
$status = 404;

$message = match ($status) {
  200 => "OK",
  404 => "Page not found",
  500 => "Server error",
  default => "Unknown status",
};

echo $message;
?>