3. Control Structures (PHP)

1️⃣ If, Else, Elseif

Used when you want to execute code based on conditions.

✅ Syntax:

if (condition) {
// code if condition is true
} elseif (another_condition) {
// code if second condition is true
} else {
// code if all conditions are false
}

✅ Example:

$marks = 75;if ($marks >= 90) {
echo "Grade A";
} elseif ($marks >= 60) {
echo "Grade B";
} else {
echo "Fail";
}

👉 Output: Grade B


2️⃣ Switch Case

Used when you have multiple possible values for a single variable.

✅ Syntax:

switch (variable) {
case value1:
// code
break;
case value2:
// code
break;
default:
// default code
}

✅ Example:

$day = "Monday";switch ($day) {
case "Monday":
echo "Start of week";
break;
case "Friday":
echo "Weekend coming";
break;
default:
echo "Normal day";
}

👉 Output: Start of week


3️⃣ Ternary Operator

Short form of if-else.

✅ Syntax:

(condition) ? value_if_true : value_if_false;

✅ Example:

$age = 18;echo ($age >= 18) ? "Adult" : "Minor";

👉 Output: Adult

👉 Useful for short conditions only.


4️⃣ Match Expression (PHP 8+)

Modern alternative to switch, more powerful and safer.

🔥 Key Features:

  • No break needed
  • Strict comparison (===)
  • Returns a value
  • Cleaner syntax

✅ Syntax:

$result = match (variable) {
value1 => result1,
value2 => result2,
default => default_result,
};

✅ Example:

$day = "Monday";$message = match ($day) {
"Monday" => "Start of week",
"Friday" => "Weekend coming",
default => "Normal day",
};echo $message;

👉 Output: Start of week


⚡ Difference (Important for Students)

FeatureSwitch CaseMatch Expression
Break neededYesNo
ComparisonLoose (==)Strict (===)
Returns valueNoYes
SyntaxLongerCleaner

💡 When to Use What?

  • if-else → Complex conditions (ranges, multiple checks)
  • switch → Many fixed values (old method)
  • ternary → Short conditions (one line)
  • match → Best modern choice (PHP 8+)