Control Structures

Master conditionals and loops to control the flow of your PHP programs.

Control Flow

Control structures let you make decisions and repeat actions in your code. Essential for building dynamic applications.

If...Else Statements

PHP Conditionals
<?php
$age = 18;

// Basic if-else
if ($age >= 18) {
    echo "You are an adult";
} else {
    echo "You are a minor";
}

// Elseif chain
$score = 85;
if ($score >= 90) {
    echo "Grade: A";
} elseif ($score >= 80) {
    echo "Grade: B";
} elseif ($score >= 70) {
    echo "Grade: C";
} else {
    echo "Grade: F";
}

// Ternary operator (short form)
$result = $age >= 18 ? "Adult" : "Minor";
echo $result;

// Null coalescing
$name = $_GET['name'] ?? "Guest";

// Comparison operators: ==, ===, !=, !==, <, >, <=, >=
?>

Switch Statement

PHP Switch
<?php
$day = "Friday";

switch ($day) {
    case "Monday":
        echo "Start of work week";
        break;
    case "Tuesday":
    case "Wednesday":
    case "Thursday":
        echo "Mid-week work";
        break;
    case "Friday":
        echo "Almost weekend!";
        break;
    case "Saturday":
    case "Sunday":
        echo "Weekend!";
        break;
    default:
        echo "Invalid day";
}

// Switch with match (PHP 8+)
$result = match($day) {
    "Monday" => "Start of week",
    "Friday" => "End of week",
    default => "Regular day"
};
?>

Pro Tip: Use switch when comparing one value against multiple conditions. It's cleaner than multiple if-else statements.

Loops

PHP Loops
<?php
// For loop - when you know iterations
for ($i = 0; $i < 5; $i++) {
    echo "Number: $i<br>";
}

// While loop - condition checked first
$count = 1;
while ($count <= 5) {
    echo "Count: $count<br>";
    $count++;
}

// Do-While - runs at least once
do {
    echo "Runs once";
} while (false);

// Foreach - iterate over arrays
$colors = ["Red", "Green", "Blue"];
foreach ($colors as $index => $color) {
    echo "$index: $color<br>";
}

// Break and Continue
for ($i = 0; $i < 10; $i++) {
    if ($i == 3) continue;  // Skip 3
    if ($i == 8) break;      // Stop at 8
    echo $i;
}
?>

Nested Loops

Nested Loops
<?php
// Multiplication table
echo "<table border='1'>";
for ($row = 1; $row <= 5; $row++) {
    echo "<tr>";
    for ($col = 1; $col <= 5; $col++) {
        echo "<td>" . ($row * $col) . "</td>";
    }
    echo "</tr>";
}
echo "</table>";

// 2D Array iteration
$matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
];
foreach ($matrix as $row) {
    foreach ($row as $value) {
        echo $value . " ";
    }
    echo "<br>";
}
?>

Hands-on Exercises

Exercise 1: Write a if-else to check if a number is even or odd
Exercise 2: Create a switch that outputs the month name for a number (1-12)
Exercise 3: Use a for loop to print the first 10 even numbers
Exercise 4: Create a while loop that counts down from 10 to 1
Exercise 5: Use foreach to print all key-value pairs from an associative array