Lesson 4 โข Beginner
Control Flow ๐
Control program logic with if/elseif/else, ternary operators, switch statements, and PHP 8's match expression.
What You'll Learn in This Lesson
- โข If / elseif / else for branching logic
- โข Nested conditions and combining with && and ||
- โข Ternary operator ? : and null coalescing ??
- โข Switch statement with break and intentional fall-through
- โข PHP 8's match expression โ the safer, cleaner switch
1๏ธโฃ If / Elseif / Else Syntax
<?php
if ($condition1) {
// runs if condition1 is true
} elseif ($condition2) {
// runs if condition2 is true
} else {
// runs if nothing above was true
}
?>Key point: PHP uses elseif (one word) or else if (two words) โ both work, but elseif is more common.
Try It: If / Elseif / Else
Build a grading system, nested conditions, ternary operator, and combined logic
// PHP Control Flow: if / elseif / else (simulated in JavaScript)
console.log("=== If / Elseif / Else ===");
console.log();
// Grading system
let score = 78;
console.log("Student score: " + score);
console.log();
if (score >= 90) {
console.log("Grade: A โ Excellent! ๐");
} else if (score >= 80) {
console.log("Grade: B โ Good job! ๐");
} else if (score >= 70) {
console.log("Grade: C โ Satisfactory โ");
} else if (score >= 60) {
console.log("Grade: D โ Needs improvement");
} el
...Try It: Switch & Match
Compare switch statement fall-through, PHP 8's match expression, and HTTP status codes
// PHP Switch Statement & Match Expression
console.log("=== Switch Statement ===");
console.log();
console.log("Use switch when comparing one variable against many values.");
console.log("Much cleaner than a long if/elseif chain!");
console.log();
let dayOfWeek = 3; // 1=Mon, 7=Sun
console.log("Day number: " + dayOfWeek);
// PHP switch statement
switch (dayOfWeek) {
case 1:
console.log("Monday โ Start of the week ๐ช");
break;
case 2:
console.log("Tuesday โ Kee
...โ ๏ธ Common Mistakes
if ($x = 5) assigns, not compares. Always use == or ===.0, "", null, "0", and empty arrays are all falsy in PHP.match() over switch in PHP 8+ โ no break needed, strict comparison by default, and it returns a value.๐ Quick Reference โ Control Flow
| Structure | Use When |
|---|---|
| if/elseif/else | Different conditions to test |
| ? : | Simple one-line if/else |
| ?? | Default value for null |
| switch | One variable, many values |
| match() | Like switch but safer (PHP 8+) |
๐ Lesson Complete!
You've mastered PHP control flow! Next, learn how to repeat code with loops.
Sign up for free to track which lessons you've completed and get learning reminders.