PHP Control Structures
Control structures are the backbone of any programming language, allowing you to control the flow of execution in your code. PHP provides several control structures that help you make decisions, repeat actions, and handle different scenarios in your applications.
Understanding these structures is essential for writing efficient, readable, and maintainable PHP code.
Conditional Statements
Conditional statements allow your code to make decisions based on certain conditions.
1. If Statement
The if
statement executes code only when a condition is true.
$age = 25;
if ($age >= 18) {
echo "You are an adult.";
}
// Output: You are an adult.
2. If-Else Statement
The if-else
statement provides an alternative path when the condition is false.
$temperature = 15;
if ($temperature > 20) {
echo "It's warm outside.";
} else {
echo "It's cool outside.";
}
// Output: It's cool outside.
3. If-Elseif-Else Statement
Use elseif
to check multiple conditions in sequence.
$score = 85;
if ($score >= 90) {
echo "Grade: A";
} elseif ($score >= 80) {
echo "Grade: B";
} elseif ($score >= 70) {
echo "Grade: C";
} elseif ($score >= 60) {
echo "Grade: D";
} else {
echo "Grade: F";
}
// Output: Grade: B
4. Switch Statement
The switch
statement is useful when comparing a variable against many values.
$dayOfWeek = "Monday";
switch ($dayOfWeek) {
case "Monday":
echo "Start of the work week!";
break;
case "Tuesday":
case "Wednesday":
case "Thursday":
echo "Midweek grind.";
break;
case "Friday":
echo "TGIF!";
break;
case "Saturday":
case "Sunday":
echo "Weekend time!";
break;
default:
echo "Invalid day.";
}
// Output: Start of the work week!
Important: Always use break
statements to prevent fall-through behavior.
5. Ternary Operator
The ternary operator provides a shorthand for simple if-else statements.
$age = 20;
$status = ($age >= 18) ? "adult" : "minor";
echo "You are an $status."; // Output: You are an adult.
// Equivalent to:
if ($age >= 18) {
$status = "adult";
} else {
$status = "minor";
}
6. Null Coalescing Operator (PHP 7+)
The null coalescing operator ??
provides a concise way to handle null values.
$username = $_GET['username'] ?? 'guest';
// Equivalent to:
$username = isset($_GET['username']) ? $_GET['username'] : 'guest';
// Chain multiple null coalescing operators
$config = $userConfig ?? $defaultConfig ?? 'fallback';
Loops
Loops allow you to execute code repeatedly until a condition is met.
1. For Loop
The for
loop is ideal when you know exactly how many iterations you need.
// Basic for loop
for ($i = 1; $i <= 5; $i++) {
echo "Iteration $i\n";
}
// Output:
// Iteration 1
// Iteration 2
// Iteration 3
// Iteration 4
// Iteration 5
// Counting backwards
for ($i = 10; $i >= 1; $i--) {
echo "$i ";
}
// Output: 10 9 8 7 6 5 4 3 2 1
2. While Loop
The while
loop continues as long as the condition remains true.
$count = 1;
while ($count <= 3) {
echo "Count: $count\n";
$count++;
}
// Output:
// Count: 1
// Count: 2
// Count: 3
// Reading a file line by line
$file = fopen("data.txt", "r");
while (($line = fgets($file)) !== false) {
echo $line;
}
fclose($file);
3. Do-While Loop
The do-while
loop executes the code block at least once before checking the condition.
$number = 1;
do {
echo "Number: $number\n";
$number++;
} while ($number <= 3);
// Output:
// Number: 1
// Number: 2
// Number: 3
// This will execute at least once even if condition is false
$x = 10;
do {
echo "This runs once even though x is not less than 5\n";
} while ($x < 5);
4. Foreach Loop
The foreach
loop is specifically designed for iterating over arrays and objects.
// Indexed array
$fruits = ["apple", "banana", "orange"];
foreach ($fruits as $fruit) {
echo "I like $fruit\n";
}
// Associative array
$person = [
"name" => "Josh Reed",
"age" => 30,
"city" => "Denver"
];
foreach ($person as $key => $value) {
echo "$key: $value\n";
}
// Output:
// name: Josh Reed
// age: 30
// city: Denver
Loop Control Statements
Break Statement
The break
statement exits the current loop immediately.
for ($i = 1; $i <= 10; $i++) {
if ($i == 5) {
break; // Exit the loop when $i equals 5
}
echo "$i ";
}
// Output: 1 2 3 4
// Break out of nested loops
for ($i = 1; $i <= 3; $i++) {
for ($j = 1; $j <= 3; $j++) {
if ($j == 2) {
break 2; // Break out of both loops
}
echo "$i-$j ";
}
}
// Output: 1-1
Continue Statement
The continue
statement skips the current iteration and moves to the next one.
for ($i = 1; $i <= 5; $i++) {
if ($i == 3) {
continue; // Skip when $i equals 3
}
echo "$i ";
}
// Output: 1 2 4 5
// Skip even numbers
for ($i = 1; $i <= 10; $i++) {
if ($i % 2 == 0) {
continue;
}
echo "$i "; // Only odd numbers
}
// Output: 1 3 5 7 9
Alternative Syntax
PHP provides alternative syntax for control structures, useful in templates.
// Alternative if syntax
<?php if ($user->isLoggedIn()): ?>
<p>Welcome back, <?= $user->getName() ?>!</p>
<?php else: ?>
<p>Please log in.</p>
<?php endif; ?>
// Alternative foreach syntax
<?php foreach ($products as $product): ?>
<div class="product">
<h3><?= $product['name'] ?></h3>
<p>$<?= $product['price'] ?></p>
</div>
<?php endforeach; ?>
// Alternative for syntax
<?php for ($i = 1; $i <= 5; $i++): ?>
<p>Item <?= $i ?></p>
<?php endfor; ?>
Practical Example: User Authentication System
Here's a practical example that combines multiple control structures:
function authenticateUser(array $credentials): array {
$response = ['success' => false, 'message' => ''];
// Check if required fields are present
if (empty($credentials['username']) || empty($credentials['password'])) {
$response['message'] = 'Username and password are required.';
return $response;
}
// Simulate user database
$users = [
'josh' => ['password' => 'secret123', 'role' => 'admin'],
'jane' => ['password' => 'password456', 'role' => 'user'],
'bob' => ['password' => 'mypass789', 'role' => 'user']
];
$username = $credentials['username'];
$password = $credentials['password'];
// Check if user exists
if (!isset($users[$username])) {
$response['message'] = 'Invalid username or password.';
return $response;
}
// Verify password
if ($users[$username]['password'] !== $password) {
$response['message'] = 'Invalid username or password.';
return $response;
}
// Authentication successful
$response['success'] = true;
$response['user'] = [
'username' => $username,
'role' => $users[$username]['role']
];
// Set welcome message based on role
switch ($users[$username]['role']) {
case 'admin':
$response['message'] = 'Welcome, Administrator!';
break;
case 'user':
$response['message'] = 'Welcome, User!';
break;
default:
$response['message'] = 'Welcome!';
}
return $response;
}
// Usage example
$loginAttempts = [
['username' => 'josh', 'password' => 'secret123'],
['username' => 'jane', 'password' => 'wrongpass'],
['username' => '', 'password' => 'somepass']
];
foreach ($loginAttempts as $index => $credentials) {
echo "Login attempt " . ($index + 1) . ":\n";
$result = authenticateUser($credentials);
if ($result['success']) {
echo "✓ " . $result['message'] . "\n";
echo " User: " . $result['user']['username'] . "\n";
echo " Role: " . $result['user']['role'] . "\n";
} else {
echo "✗ " . $result['message'] . "\n";
}
echo "\n";
}
Best Practices
1. Use Appropriate Control Structures
// Good: Use foreach for arrays
foreach ($items as $item) {
processItem($item);
}
// Avoid: Using for loop with arrays when foreach is more appropriate
for ($i = 0; $i < count($items); $i++) {
processItem($items[$i]);
}
2. Keep Conditions Simple and Readable
// Good: Clear and readable
if ($user->isActive() && $user->hasPermission('edit')) {
allowEdit();
}
// Better: Extract complex conditions into variables
$canEdit = $user->isActive() && $user->hasPermission('edit');
if ($canEdit) {
allowEdit();
}
3. Avoid Deep Nesting
// Avoid: Deep nesting is hard to read
if ($user) {
if ($user->isActive()) {
if ($user->hasPermission('edit')) {
// do something
}
}
}
// Better: Early returns reduce nesting
if (!$user) {
return;
}
if (!$user->isActive()) {
return;
}
if (!$user->hasPermission('edit')) {
return;
}
// do something
Summary
PHP control structures are essential tools for building dynamic and responsive applications. Key takeaways:
- Conditional statements (
if
,switch
, ternary) help your code make decisions - Loops (
for
,while
,foreach
) allow repetitive operations - Loop control (
break
,continue
) provides fine-grained control over execution flow - Alternative syntax makes templates more readable
- Best practices include using appropriate structures, keeping conditions simple, and avoiding deep nesting
Mastering these control structures will make you a more effective PHP developer and help you write cleaner, more maintainable code.
Thanks for reading! Practice using these control structures in different scenarios to become more comfortable with controlling the flow of your PHP applications.