beginner Step 3 of 16

Control Structures and Loops

PHP Programming

Control Structures and Loops

Control structures determine the flow of execution in your PHP programs. PHP provides familiar constructs like if/elseif/else, switch/case, and several loop types. PHP 8.0 introduced the match expression, a more powerful and safer alternative to switch that uses strict comparison and returns values. Understanding these constructs is essential for implementing business logic, processing data, and controlling how your application responds to different conditions.

If/Elseif/Else

<?php
$score = 85;

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

// Ternary shorthand
$status = ($score >= 60) ? "Pass" : "Fail";

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

// Alternative syntax for templates
?>
<?php if ($user): ?>
    <p>Welcome, <?= $user['name'] ?>!</p>
<?php else: ?>
    <p>Please log in.</p>
<?php endif; ?>

Match Expression (PHP 8.0+)

<?php
// match uses strict comparison and returns a value
$status_code = 404;

$message = match($status_code) {
    200 => "OK",
    301 => "Moved Permanently",
    404 => "Not Found",
    500 => "Internal Server Error",
    default => "Unknown Status"
};
echo $message;  // "Not Found"

// Multiple values per arm
$day = "Saturday";
$type = match($day) {
    "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" => "Weekday",
    "Saturday", "Sunday" => "Weekend",
};

// Match with no argument (like if/elseif)
$age = 25;
$category = match(true) {
    $age < 13 => "child",
    $age < 18 => "teenager",
    $age < 65 => "adult",
    default => "senior"
};

Loops

<?php
// For loop
for ($i = 0; $i < 5; $i++) {
    echo "$i ";  // 0 1 2 3 4
}

// While loop
$count = 0;
while ($count < 5) {
    echo "$count ";
    $count++;
}

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

// Foreach — the most common loop in PHP
$fruits = ["apple", "banana", "cherry"];
foreach ($fruits as $fruit) {
    echo "$fruit
";
}

// Foreach with key
$person = ["name" => "Alice", "age" => 30, "city" => "NYC"];
foreach ($person as $key => $value) {
    echo "$key: $value
";
}

// Foreach with index
foreach ($fruits as $index => $fruit) {
    echo "$index: $fruit
";
}

// Modifying array values in foreach
$prices = [10, 20, 30];
foreach ($prices as &$price) {  // Note the & for reference
    $price *= 1.1;  // Add 10% tax
}
unset($price);  // Always unset the reference after the loop
print_r($prices);  // [11, 22, 33]

// Break and continue
for ($i = 0; $i < 100; $i++) {
    if ($i % 2 === 0) continue;  // Skip even numbers
    if ($i > 10) break;           // Stop at 10
    echo "$i ";  // 1 3 5 7 9
}
?>

Array Functions for Iteration

<?php
$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// array_map — transform each element
$squared = array_map(fn($n) => $n ** 2, $numbers);

// array_filter — keep matching elements
$evens = array_filter($numbers, fn($n) => $n % 2 === 0);

// array_reduce — accumulate to single value
$sum = array_reduce($numbers, fn($carry, $n) => $carry + $n, 0);

// Chaining (less elegant than JS but works)
$result = array_map(
    fn($n) => $n * 2,
    array_filter($numbers, fn($n) => $n > 5)
);
print_r($result);  // [12, 14, 16, 18, 20]
?>
Pro tip: Prefer match over switch in PHP 8+. The match expression uses strict comparison (preventing type-juggling bugs), returns a value directly, does not require break statements, and throws an error if no arm matches (unless you specify a default). It is safer and more concise in every way.

Key Takeaways

  • PHP provides if/elseif/else, switch, and the modern match expression (PHP 8.0+) for conditional logic.
  • The foreach loop is the most common loop in PHP for iterating over arrays with as $key => $value.
  • Use &$var in foreach to modify array values by reference, but always unset() the reference afterward.
  • Array functions like array_map, array_filter, and array_reduce provide functional-style data processing.
  • The match expression is safer than switch: it uses strict comparison and throws on unmatched values.