Introduction
Module 3: Mastering Control Structures1. Conditional Statements (if, else, switch)Conditional statements allow PHP to make decisions based on conditions, directing the program’s flow.If, Else, ElseifThe if statement executes code if a condition is true. else handles the false case, and elseif checks additional conditions.Syntax:
if (condition) {
// Code if true
} elseif (another_condition) {
// Code if another_condition is true
} else {
// Code if all conditions are false
}<?php
$age = 20;
if ($age >= 18) {
echo "You are an adult.";
} else {
echo "You are a minor.";
}
// Output: You are an adult.
?><?php
$age = isset($_POST['age']) ? (int)$_POST['age'] : 0;
$ticketPrice = 10.00;
if ($age < 12) {
$discount = 0.5; // 50% off for children
} elseif ($age >= 60) {
$discount = 0.3; // 30% off for seniors
} else {
$discount = 0; // No discount
}
$finalPrice = $ticketPrice * (1 - $discount);
echo "Ticket Price: $" . number_format($finalPrice, 2);
// Input age=10, Output: Ticket Price: $5.00
?>switch (expression) {
case value1:
// Code
break;
case value2:
// Code
break;
default:
// Code if no match
}<?php
$day = "Monday";
switch ($day) {
case "Monday":
echo "Start of the week!";
break;
case "Friday":
echo "Weekend is near!";
break;
default:
echo "Regular day.";
}
// Output: Start of the week!
?><?php
$category = isset($_GET['category']) ? $_GET['category'] : "default";
switch ($category) {
case "electronics":
$products = ["Phone", "Laptop", "Tablet"];
break;
case "clothing":
$products = ["Shirt", "Jeans", "Jacket"];
break;
default:
$products = ["No products available"];
}
echo "Products: " . implode(", ", $products);
// Input category=electronics, Output: Products: Phone, Laptop, Tablet
?>- Intuitive for decision-making logic.
- Flexible for handling multiple conditions.
- Switch is efficient for multiple fixed values.
- Nested if statements can become unreadable.
- switch requires break to prevent fall-through errors.
- Loose comparison (==) in switch can cause bugs.
- Ternary Operator: For simple conditions (e.g., $message = $age >= 18 ? "Adult" : "Minor";).
- Match Expression (PHP 8): A modern alternative to switch (covered later).
- Arrays for Mapping: Use arrays for simple key-value mappings instead of switch.
- Use === for strict comparisons in if and switch.
- Keep if statements shallow; refactor nested conditions into functions.
- Always include break in switch cases or use match for safer execution.
- Validate user inputs to prevent unexpected behavior.
2. Loops (for, while, do-while, foreach)Loops execute code repeatedly based on conditions or iterations, ideal for processing lists, generating content, or automating tasks.For LoopThe for loop runs a fixed number of times, using an initializer, condition, and increment.Syntax:
for (initialization; condition; increment) {
// Code
}<?php
for ($i = 1; $i <= 5; $i++) {
echo "Number: $i<br>";
}
// Output:
// Number: 1
// Number: 2
// Number: 3
// Number: 4
// Number: 5
?><?php
$totalPages = 10;
$currentPage = isset($_GET['page']) ? (int)$_GET['page'] : 1;
for ($i = 1; $i <= $totalPages; $i++) {
$class = ($i === $currentPage) ? "active" : "";
echo "<a class='$class' href='?page=$i'>$i</a> ";
}
// Output: <a class='' href='?page=1'>1</a> <a class='active' href='?page=2'>2</a> ...
?>while (condition) {
// Code
}<?php
$count = 1;
while ($count <= 5) {
echo "Count: $count<br>";
$count++;
}
// Output:
// Count: 1
// Count: 2
// Count: 3
// Count: 4
// Count: 5
?><?php
$stock = 10;
$orderQty = 3;
while ($stock > 0 && $orderQty > 0) {
$stock -= $orderQty;
echo "Order processed. Remaining stock: $stock<br>";
}
// Output:
// Order processed. Remaining stock: 7
// Order processed. Remaining stock: 4
// Order processed. Remaining stock: 1
?>do {
// Code
} while (condition);<?php
$count = 1;
do {
echo "Iteration: $count<br>";
$count++;
} while ($count <= 3);
// Output:
// Iteration: 1
// Iteration: 2
// Iteration: 3
?><?php
$input = "";
do {
$input = isset($_POST['email']) ? $_POST['email'] : "";
if (!filter_var($input, FILTER_VALIDATE_EMAIL)) {
echo "Invalid email, try again.<br>";
}
} while (!filter_var($input, FILTER_VALIDATE_EMAIL) && $input !== "");
echo $input ? "Valid email: $input" : "No input provided";
?>foreach ($array as $value) {
// Code
}
foreach ($array as $key => $value) {
// Code
}<?php
$colors = ["red", "green", "blue"];
foreach ($colors as $color) {
echo "Color: $color<br>";
}
// Output:
// Color: red
// Color: green
// Color: blue
?><?php
$cart = [
"book" => 19.99,
"pen" => 2.99,
"notebook" => 5.49
];
$total = 0;
foreach ($cart as $item => $price) {
echo "$item: $$price<br>";
$total += $price;
}
echo "Total: $$total";
// Output:
// book: $19.99
// pen: $2.99
// notebook: $5.49
// Total: $28.47
?>- Automate repetitive tasks efficiently.
- foreach simplifies array iteration.
- do-while ensures at least one execution.
- Infinite loops can crash servers (e.g., while (true) {}).
- Nested loops can reduce readability.
- foreach can’t modify array keys directly.
- Array Functions: Use array_map(), array_filter() for functional programming.
- Recursion: For complex iterations, though it’s memory-intensive.
- List Comprehension (Python-like): Not native to PHP, but frameworks like Laravel offer similar utilities.
- Initialize loop variables to avoid undefined errors.
- Use break or continue sparingly for clarity.
- Avoid deep nesting; refactor into functions.
- Use foreach for arrays unless index manipulation is needed.
3. Break & ContinueBreakThe break statement exits a loop or switch immediately.Example:
<?php
for ($i = 1; $i <= 10; $i++) {
if ($i === 6) {
break; // Exit loop when $i is 6
}
echo "$i ";
}
// Output: 1 2 3 4 5
?><?php
$stock = 5;
$orders = [2, 3, 1, 4];
foreach ($orders as $order) {
if ($stock < $order) {
break; // Stop if stock is insufficient
}
$stock -= $order;
echo "Processed order of $order. Stock left: $stock<br>";
}
// Output:
// Processed order of 2. Stock left: 3
// Processed order of 3. Stock left: 0
?><?php
for ($i = 1; $i <= 5; $i++) {
if ($i % 2 === 0) {
continue; // Skip even numbers
}
echo "$i ";
}
// Output: 1 3 5
?><?php
$inputs = ["john@example.com", "invalid", "alice@example.com"];
foreach ($inputs as $email) {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
continue; // Skip invalid emails
}
echo "Valid email: $email<br>";
}
// Output:
// Valid email: john@example.com
// Valid email: alice@example.com
?>- break prevents unnecessary iterations.
- continue improves efficiency by skipping irrelevant cases.
- Overuse can make code harder to follow.
- Can lead to logic errors if misused.
- Use break and continue only when necessary.
- Document their purpose with comments.
- Consider refactoring complex loops into functions.
4. PHP 8: Match vs. SwitchMatch ExpressionIntroduced in PHP 8, the match expression is a concise, type-safe alternative to switch. It returns a value and doesn’t require break.Syntax:
$result = match (expression) {
value1 => result1,
value2 => result2,
default => default_result,
};<?php
$status = 1;
$result = match ($status) {
1 => "Active",
2 => "Inactive",
default => "Unknown",
};
echo $result; // Output: Active
?><?php
$role = "admin";
// Using switch
switch ($role) {
case "admin":
$access = "Full";
break;
case "editor":
$access = "Limited";
break;
default:
$access = "None";
}
echo "Switch Access: $access<br>";
// Using match
$access = match ($role) {
"admin" => "Full",
"editor" => "Limited",
default => "None",
};
echo "Match Access: $access";
?><?php
$userRole = isset($_GET['role']) ? $_GET['role'] : "guest";
$permissions = match ($userRole) {
"admin" => ["read", "write", "delete"],
"editor" => ["read", "write"],
"viewer" => ["read"],
default => [],
};
echo "Permissions: " . implode(", ", $permissions);
// Input role=admin, Output: Permissions: read, write, delete
?>- Concise and returns a value.
- Strict comparison (===) by default.
- No fall-through errors.
- Supports complex expressions (e.g., $x > 10 => "High").
- Not suitable for complex logic within cases.
- Requires PHP 8+.
- Familiar to developers from other languages.
- Supports complex logic in cases.
- Risk of fall-through without break.
- Verbose for simple mappings.
- Use match for simple value mappings.
- Use switch for complex case logic.
- Ensure strict typing with declare(strict_types=1);.
- Test match expressions in PHP 8.2+ environments.
Advanced Scenarios
- Dynamic Form Validation: Validate multiple form fields using loops and conditionals:php
<?php $fields = ["name" => $_POST['name'] ?? "", "email" => $_POST['email'] ?? ""]; $errors = []; foreach ($fields as $field => $value) { if (empty($value)) { $errors[] = "Error: $field is required."; continue; } if ($field === "email" && !filter_var($value, FILTER_VALIDATE_EMAIL)) { $errors[] = "Error: Invalid email format."; } } echo empty($errors) ? "Form is valid!" : implode("<br>", $errors); ?> - Inventory Management System: Process stock updates with loops and break:php
<?php $inventory = ["item1" => 10, "item2" => 5, "item3" => 0]; $order = ["item1" => 3, "item2" => 6]; foreach ($order as $item => $qty) { if (!isset($inventory[$item]) || $inventory[$item] < $qty) { echo "Insufficient stock for $item.<br>"; break; } $inventory[$item] -= $qty; echo "Processed $qty of $item. New stock: {$inventory[$item]}<br>"; } ?> - Role-Based Dashboard: Use match to customize user interfaces:php
<?php declare(strict_types=1); function getDashboardContent(string $role): string { return match ($role) { "admin" => "<h1>Admin Dashboard: Manage Users, Settings</h1>", "editor" => "<h1>Editor Dashboard: Create Content</h1>", "viewer" => "<h1>Viewer Dashboard: View Reports</h1>", default => "<h1>Access Denied</h1>", }; } $userRole = "editor"; echo getDashboardContent($userRole); // Output: <h1>Editor Dashboard: Create Content</h1> ?>
ConclusionCongratulations on mastering Module 3: Control Structures! You’ve learned how to use conditional statements (if, else, switch), loops (for, while, do-while, foreach), break and continue, and the modern PHP 8 match expression. With real-life examples like ticket pricing, pagination, and role-based dashboards, you’re ready to build dynamic, interactive web applications. By following best practices like strict typing and clear loop structures, you’ll write clean, efficient PHP code.
No comments:
Post a Comment
Thanks for your valuable comment...........
Md. Mominul Islam