PHP Control Statements - break and continue
Learning Objectives
- Master PHP programming concepts
- Write clean, maintainable code
- Apply best practices
- Build dynamic applications
Introduction to Control Statements
Welcome to our session on PHP Control Statements, specifically the break and continue statements. These powerful control structures allow you to alter the normal flow of loops, giving you precise control over how your code executes.
Think of control statements as traffic signals in your code—they direct the flow, telling the program when to stop, when to skip ahead, and when to proceed normally.
In this lesson, we'll explore how break and continue work, how they differ, and how you can use them to write more efficient and readable code. These control statements work with all loop types we've covered so far: for, while, do-while, and foreach loops.
The break Statement
The break statement terminates the execution of a loop completely and transfers control to the statement following the loop.
Syntax
break;
The break statement can also include a numeric argument that specifies how many nested loops to exit:
break n; // Exit n levels of nested loops
Basic Example: Finding an Element
<?php
$numbers = [1, 3, 5, 7, 9, 11, 13, 15];
$searchFor = 9;
$found = false;
$position = -1;
for ($i = 0; $i < count($numbers); $i++) {
echo "Checking position $i: " . $numbers[$i] . "<br>";
if ($numbers[$i] === $searchFor) {
$found = true;
$position = $i;
echo "Found $searchFor at position $position!<br>";
break; // Exit the loop immediately
}
}
if ($found) {
echo "Search complete. The number $searchFor was found at position $position.";
} else {
echo "Search complete. The number $searchFor was not found in the array.";
}
?>
Output:
Checking position 0: 1 Checking position 1: 3 Checking position 2: 5 Checking position 3: 7 Checking position 4: 9 Found 9 at position 4! Search complete. The number 9 was found at position 4.
In this example, the break statement terminates the loop as soon as the value is found. This is more efficient than continuing to check the remaining elements unnecessarily.
Think of break like finding what you're looking for in a stack of documents—once you've found it, there's no need to keep searching through the rest of the papers.
Advanced Example: Breaking from Nested Loops
<?php
// 2D grid search example
$grid = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]
];
$searchFor = 11;
$found = false;
echo "<h4>Searching for $searchFor in the grid:</h4>";
// Display the grid
echo "<table border='1' style='border-collapse: collapse'>";
foreach ($grid as $row) {
echo "<tr>";
foreach ($row as $cell) {
echo "<td style='padding: 10px'>$cell</td>";
}
echo "</tr>";
}
echo "</table><br>";
// Search the grid
for ($row = 0; $row < count($grid); $row++) {
for ($col = 0; $col < count($grid[$row]); $col++) {
echo "Checking position [$row][$col]: " . $grid[$row][$col] . "<br>";
if ($grid[$row][$col] === $searchFor) {
$found = true;
echo "<strong>Found $searchFor at position [$row][$col]!</strong><br>";
break 2; // Break out of BOTH loops
}
}
}
if ($found) {
echo "Search complete. The number $searchFor was found in the grid.";
} else {
echo "Search complete. The number $searchFor was not found in the grid.";
}
?>
Output:
Searching for 11 in the grid:
| 1 | 2 | 3 | 4 |
| 5 | 6 | 7 | 8 |
| 9 | 10 | 11 | 12 |
| 13 | 14 | 15 | 16 |
Checking position [0][0]: 1 Checking position [0][1]: 2 Checking position [0][2]: 3 Checking position [0][3]: 4 Checking position [1][0]: 5 Checking position [1][1]: 6 Checking position [1][2]: 7 Checking position [1][3]: 8 Checking position [2][0]: 9 Checking position [2][1]: 10 Checking position [2][2]: 11 Found 11 at position [2][2]! Search complete. The number 11 was found in the grid.
This example demonstrates the numeric argument with break. Here, break 2 exits both the inner and outer loops when the value is found. Without the numeric argument, only the inner loop would terminate, and the outer loop would continue to the next iteration.
Think of this like searching through a multi-floor building—when you find what you're looking for, break 2 lets you exit the building entirely, not just the room you're in.
The continue Statement
The continue statement skips the rest of the current loop iteration and proceeds to the next iteration. Unlike break, it doesn't terminate the loop entirely—it just jumps ahead.
Syntax
continue;
Like break, the continue statement can also include a numeric argument:
continue n; // Skip to the next iteration of the nth enclosing loop
Basic Example: Processing Only Even Numbers
<?php
$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
$sum = 0;
echo "Adding only even numbers:<br>";
foreach ($numbers as $number) {
// Skip odd numbers
if ($number % 2 !== 0) {
echo "Skipping $number (odd)<br>";
continue;
}
// Process even numbers
$sum += $number;
echo "Adding $number to sum (now $sum)<br>";
}
echo "Final sum of even numbers: $sum";
?>
Output:
Adding only even numbers: Skipping 1 (odd) Adding 2 to sum (now 2) Skipping 3 (odd) Adding 4 to sum (now 6) Skipping 5 (odd) Adding 6 to sum (now 12) Skipping 7 (odd) Adding 8 to sum (now 20) Skipping 9 (odd) Adding 10 to sum (now 30) Final sum of even numbers: 30
In this example, continue allows us to skip the odd numbers and only process the even ones. When an odd number is encountered, the rest of the loop body is skipped, and execution jumps to the next iteration.
Think of continue like sorting mail—when you come across junk mail, you immediately discard it and continue to the next piece without further processing.
Advanced Example: Nested Loops with continue
<?php
// Generate a multiplication table with some exceptions
echo "<h4>Multiplication Table (skipping multiples of 5)</h4>";
echo "<table border='1' style='border-collapse: collapse'>";
// Table header
echo "<tr><th>×</th>";
for ($i = 1; $i <= 10; $i++) {
echo "<th>$i</th>";
}
echo "</tr>";
// Table body
for ($row = 1; $row <= 10; $row++) {
echo "<tr>";
echo "<th>$row</th>"; // Row header
for ($col = 1; $col <= 10; $col++) {
$result = $row * $col;
// Skip multiples of 5
if ($result % 5 === 0) {
echo "<td style='background-color: #ffd0d0;'>Skip</td>";
continue;
}
echo "<td>$result</td>";
}
echo "</tr>";
}
echo "</table>";
?>
Output:
Multiplication Table (skipping multiples of 5)
| × | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
|---|---|---|---|---|---|---|---|---|---|---|
| 1 | 1 | 2 | 3 | 4 | Skip | 6 | 7 | 8 | 9 | Skip |
| 2 | 2 | 4 | 6 | 8 | Skip | 12 | 14 | 16 | 18 | Skip |
This example uses the continue statement to skip certain calculations in a multiplication table. When a multiple of 5 is encountered, we display "Skip" instead of the actual value and proceed to the next cell.
Think of this like following a recipe but skipping certain ingredients that you don't like or are allergic to—you still complete the recipe, just without those specific items.
Using continue with a Numeric Argument
<?php
// Process a 2D array, skipping certain sub-arrays entirely
$data = [
[1, 2, 3, 4],
[5, -1, 7, 8], // Contains a negative value
[9, 10, 11, 12],
[13, 14, -2, 16], // Contains a negative value
[17, 18, 19, 20]
];
echo "Processing only sub-arrays without negative values:<br>";
for ($i = 0; $i < count($data); $i++) {
echo "Checking sub-array $i: [" . implode(", ", $data[$i]) . "]<br>";
// Check if this sub-array contains any negative values
for ($j = 0; $j < count($data[$i]); $j++) {
if ($data[$i][$j] < 0) {
echo "Found negative value " . $data[$i][$j] . " at position [$i][$j], skipping entire sub-array<br>";
continue 2; // Skip to the next iteration of the outer loop
}
}
// Process the sub-array (only reached if no negatives were found)
$sum = array_sum($data[$i]);
echo "Processing sub-array $i, sum: $sum<br>";
echo "<hr>";
}
?>
Output:
Processing only sub-arrays without negative values: Checking sub-array 0: [1, 2, 3, 4] Processing sub-array 0, sum: 10 ------------------------------ Checking sub-array 1: [5, -1, 7, 8] Found negative value -1 at position [1][1], skipping entire sub-array Checking sub-array 2: [9, 10, 11, 12] Processing sub-array 2, sum: 42 ------------------------------ Checking sub-array 3: [13, 14, -2, 16] Found negative value -2 at position [3][2], skipping entire sub-array Checking sub-array 4: [17, 18, 19, 20] Processing sub-array 4, sum: 74 ------------------------------
This example demonstrates continue with a numeric argument. By using continue 2, we skip the rest of the inner loop and the current iteration of the outer loop when a negative value is found. This allows us to efficiently skip processing sub-arrays that don't meet our criteria.
Think of this like inspecting a batch of products—if you find a defect in any item from a batch, you might decide to reject the entire batch and move on to the next one.
break vs. continue: When to Use Each
Understanding when to use break versus continue is important for writing efficient and readable code:
- Use break when:
- You've found what you're searching for and don't need to check the rest of the elements
- An error or exceptional condition makes continuing the loop pointless or dangerous
- You've reached a natural endpoint in your processing logic
- Use continue when:
- You want to skip processing for certain elements but continue with others
- You're filtering or selecting items that match specific criteria
- Some iterations can be skipped to improve efficiency, but you still need to process the remaining elements
Control Statements in Different Loop Types
The break and continue statements work with all PHP loop types, but with some important differences to keep in mind:
In for Loops
<?php
echo "Using break in a for loop:<br>";
for ($i = 1; $i <= 10; $i++) {
if ($i == 5) {
echo "Reached 5, breaking the loop<br>";
break;
}
echo "Iteration: $i<br>";
}
echo "<hr>";
echo "Using continue in a for loop:<br>";
for ($i = 1; $i <= 10; $i++) {
if ($i % 3 == 0) {
echo "Skipping $i (multiple of 3)<br>";
continue;
}
echo "Processing: $i<br>";
}
?>
Output:
Using break in a for loop: Iteration: 1 Iteration: 2 Iteration: 3 Iteration: 4 Reached 5, breaking the loop ------------------------------ Using continue in a for loop: Processing: 1 Processing: 2 Skipping 3 (multiple of 3) Processing: 4 Processing: 5 Skipping 6 (multiple of 3) Processing: 7 Processing: 8 Skipping 9 (multiple of 3) Processing: 10
In for loops, continue skips the remainder of the loop body but still executes the increment expression. This is important to understand, as the counter variable will still be updated when continue is used.
In while and do-while Loops
<?php
echo "Using break in a while loop:<br>";
$counter = 1;
while ($counter <= 10) {
if ($counter == 5) {
echo "Reached 5, breaking the loop<br>";
break;
}
echo "Iteration: $counter<br>";
$counter++;
}
echo "<hr>";
echo "Using continue in a while loop:<br>";
$counter = 1;
while ($counter <= 10) {
if ($counter % 3 == 0) {
echo "Skipping $counter (multiple of 3)<br>";
$counter++; // Important! Must increment before continue
continue;
}
echo "Processing: $counter<br>";
$counter++;
}
?>
Output:
Using break in a while loop: Iteration: 1 Iteration: 2 Iteration: 3 Iteration: 4 Reached 5, breaking the loop ------------------------------ Using continue in a while loop: Processing: 1 Processing: 2 Skipping 3 (multiple of 3) Processing: 4 Processing: 5 Skipping 6 (multiple of 3) Processing: 7 Processing: 8 Skipping 9 (multiple of 3) Processing: 10
Important Note:
In while and do-while loops, you must update your counter variable before using continue, or you'll create an infinite loop! Unlike for loops, the increment isn't built into the loop structure.
This is a common source of bugs—always make sure your loop variable is properly updated before using continue in while or do-while loops.
In foreach Loops
<?php
echo "Using break in a foreach loop:<br>";
$fruits = ["Apple", "Banana", "Cherry", "Durian", "Elderberry"];
foreach ($fruits as $index => $fruit) {
if ($fruit == "Durian") {
echo "Found Durian, breaking the loop<br>";
break;
}
echo "Fruit #" . ($index + 1) . ": $fruit<br>";
}
echo "<hr>";
echo "Using continue in a foreach loop:<br>";
$scores = ["John" => 85, "Mary" => 92, "Bob" => 67, "Alice" => 95, "Tom" => 78];
foreach ($scores as $student => $score) {
if ($score < 80) {
echo "Skipping $student (score below 80)<br>";
continue;
}
echo "$student has a good score: $score<br>";
}
?>
Output:
Using break in a foreach loop: Fruit #1: Apple Fruit #2: Banana Fruit #3: Cherry Found Durian, breaking the loop ------------------------------ Using continue in a foreach loop: John has a good score: 85 Mary has a good score: 92 Skipping Bob (score below 80) Alice has a good score: 95 Skipping Tom (score below 80)
In foreach loops, continue skips to the next element in the array or object. You don't need to worry about counter variables since foreach automatically handles the iteration.
Real-World Examples
Form Validation
Control statements are useful for form validation logic:
<?php
// Simulated form data
$formData = [
"username" => "john_doe",
"email" => "john@example.com",
"password" => "pass123",
"age" => "25",
"terms" => "yes"
];
// Required fields
$requiredFields = ["username", "email", "password", "terms"];
// Validation rules
$validationRules = [
"username" => "/^[a-zA-Z0-9_]{3,20}$/",
"email" => "/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/",
"password" => "/^.{6,}$/",
"age" => "/^[0-9]+$/"
];
// Validate the form
$errors = [];
$isValid = true;
foreach ($formData as $field => $value) {
// Skip fields that don't have validation rules
if (!isset($validationRules[$field])) {
echo "Field '$field' doesn't have validation rules, skipping...<br>";
continue;
}
// Check if required field is empty
if (in_array($field, $requiredFields) && empty($value)) {
$errors[] = "Field '$field' is required but empty";
$isValid = false;
continue; // No need to perform pattern validation if empty
}
// Validate against pattern
if (!preg_match($validationRules[$field], $value)) {
$errors[] = "Field '$field' has invalid format: '$value'";
$isValid = false;
} else {
echo "Field '$field' is valid: '$value'<br>";
}
}
// Check final validation result
if ($isValid) {
echo "<hr>Form is valid! Processing data...";
} else {
echo "<hr>Form has errors:<br>";
foreach ($errors as $error) {
echo "- $error<br>";
}
}
?>
Output:
Field 'username' is valid: 'john_doe' Field 'email' is valid: 'john@example.com' Field 'password' is valid: 'pass123' Field 'age' is valid: '25' Field 'terms' doesn't have validation rules, skipping... ------------------------------ Form is valid! Processing data...
In this form validation example, continue is used to skip fields that don't need further validation, making the code more efficient and easier to follow.
Data Processing with Error Handling
Use break to handle error conditions in data processing:
<?php
// Simulate processing a batch of records
$records = [
["id" => 1, "name" => "John Smith", "email" => "john@example.com"],
["id" => 2, "name" => "Jane Doe", "email" => "jane@example.com"],
["id" => 3, "name" => "", "email" => "missing.name@example.com"], // Missing name
["id" => 4, "name" => "Bob Johnson", "email" => "bob@example.com"],
["id" => 5, "name" => "Alice Brown", "email" => "invalid-email"] // Invalid email
];
$batchId = "BATCH-" . date("Ymd-His");
$successCount = 0;
$errorCount = 0;
$continueOnError = true; // Toggle to control error handling behavior
echo "Starting to process batch: $batchId<br>";
echo "<hr>";
foreach ($records as $index => $record) {
echo "Processing record #" . ($index + 1) . " (ID: " . $record["id"] . ")<br>";
// Validate record
$errors = [];
if (empty($record["name"])) {
$errors[] = "Name is required";
}
if (empty($record["email"]) || !filter_var($record["email"], FILTER_VALIDATE_EMAIL)) {
$errors[] = "Valid email is required";
}
// Check for validation errors
if (!empty($errors)) {
$errorCount++;
echo "Validation errors found:<br>";
foreach ($errors as $error) {
echo "- $error<br>";
}
if ($continueOnError) {
echo "Skipping this record and continuing with the next one...<br>";
echo "<hr>";
continue;
} else {
echo "Aborting batch processing due to errors<br>";
break;
}
}
// Process the valid record (in a real app, this might be a database insert)
echo "Record processed successfully: " . $record["name"] . " <" . $record["email"] . "><br>";
$successCount++;
echo "<hr>";
}
// Final report
echo "Batch processing complete<br>";
echo "Successful records: $successCount<br>";
echo "Failed records: $errorCount<br>";
echo "Total records: " . count($records) . "<br>";
if ($continueOnError) {
echo "Errors were skipped during processing";
} else {
echo "Processing stopped at the first error";
}
?>
Output (with continueOnError = true):
Starting to process batch: BATCH-20250427-123456 ------------------------------ Processing record #1 (ID: 1) Record processed successfully: John Smith <john@example.com> ------------------------------ Processing record #2 (ID: 2) Record processed successfully: Jane Doe <jane@example.com> ------------------------------ Processing record #3 (ID: 3) Validation errors found: - Name is required Skipping this record and continuing with the next one... ------------------------------ Processing record #4 (ID: 4) Record processed successfully: Bob Johnson <bob@example.com> ------------------------------ Processing record #5 (ID: 5) Validation errors found: - Valid email is required Skipping this record and continuing with the next one... ------------------------------ Batch processing complete Successful records: 3 Failed records: 2 Total records: 5 Errors were skipped during processing
This example shows how break and continue can be used for error handling in a data processing scenario. By toggling the $continueOnError variable, you can control whether to skip records with errors or abort the entire batch when an error is encountered.
Best Practices and Pitfalls
Best Practices
- Use sparingly: While control statements are powerful, overusing them can make your code difficult to follow. Code with too many
breakandcontinuestatements may indicate a design that could be improved. - Document usage: When using more complex patterns, especially with numeric arguments or in nested loops, add comments explaining the logic and purpose.
- Be careful with while/do-while: Always ensure counter variables are properly updated before using
continuein these loops. - Consider refactoring: If you find yourself using many nested loops with complex break/continue logic, consider refactoring into smaller functions or using other programming patterns for better readability.
- Use early returns in functions: In functions, returning early often leads to cleaner code than using break statements in loops.
Common Pitfalls
Infinite Loops with continue
<?php
// INCORRECT - creates an infinite loop
$i = 0;
while ($i < 10) {
if ($i == 5) {
// Oops! We forgot to increment $i before continuing
continue;
}
echo $i . " ";
$i++;
}
// CORRECT
$i = 0;
while ($i < 10) {
if ($i == 5) {
$i++; // Increment before continuing
continue;
}
echo $i . " ";
$i++;
}
?>
The first example creates an infinite loop because when $i reaches 5, the continue statement skips the increment and the condition $i == 5 will always be true.
Break Only Exits One Level of Nesting
<?php
// INCORRECT - break only exits the inner loop
$found = false;
for ($i = 0; $i < 5; $i++) {
for ($j = 0; $j < 5; $j++) {
if ($i * $j == 6) {
echo "Found it: $i * $j = 6<br>";
$found = true;
break; // This only breaks out of the inner loop
}
}
if ($found) {
// We need this extra check to break out of the outer loop
break;
}
}
// CORRECT - use break with a numeric argument
for ($i = 0; $i < 5; $i++) {
for ($j = 0; $j < 5; $j++) {
if ($i * $j == 6) {
echo "Found it: $i * $j = 6<br>";
break 2; // This breaks out of both loops
}
}
}
?>
By default, break only exits the innermost loop. If you need to exit multiple levels of nested loops, use the numeric argument or restructure your code.
Overusing Control Statements
<?php
// HARD TO READ - too many control statements
function processItems($items) {
foreach ($items as $item) {
if (empty($item['id'])) {
continue;
}
if ($item['type'] == 'special') {
if ($item['priority'] > 3) {
// Process high-priority special items
} else {
continue;
}
} else {
if ($item['status'] == 'active') {
if ($item['value'] > 100) {
// Process high-value active items
} else {
continue;
}
} else {
continue;
}
}
}
}
// BETTER - restructured logic
function processItemsBetter($items) {
foreach ($items as $item) {
// Skip invalid items
if (empty($item['id'])) {
continue;
}
// Process special items
if ($item['type'] == 'special' && $item['priority'] > 3) {
// Process high-priority special items
continue;
}
// Process regular items
if ($item['status'] == 'active' && $item['value'] > 100) {
// Process high-value active items
}
}
}
?>
Excessive use of control statements can make your code hard to follow. When possible, restructure your logic to be more straightforward and use early filtering to reduce nesting.
Alternatives to Control Statements
While break and continue are useful, sometimes there are cleaner alternatives:
Using Array Functions
<?php
// Using break to find an element
$numbers = [1, 3, 5, 7, 9, 11, 13, 15];
$searchFor = 9;
$position = -1;
for ($i = 0; $i < count($numbers); $i++) {
if ($numbers[$i] === $searchFor) {
$position = $i;
break;
}
}
echo "Using break: Found $searchFor at position $position<br>";
// Alternative using array_search()
$position = array_search($searchFor, $numbers);
echo "Using array_search(): Found $searchFor at position $position<br>";
echo "<hr>";
// Using continue to filter elements
$values = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
$evenValues = [];
foreach ($values as $value) {
if ($value % 2 != 0) {
continue; // Skip odd numbers
}
$evenValues[] = $value;
}
echo "Using continue: Even values: " . implode(", ", $evenValues) . "<br>";
// Alternative using array_filter()
$evenValues = array_filter($values, function($value) {
return $value % 2 == 0;
});
echo "Using array_filter(): Even values: " . implode(", ", $evenValues) . "<br>";
?>
Output:
Using break: Found 9 at position 4 Using array_search(): Found 9 at position 4 ------------------------------ Using continue: Even values: 2, 4, 6, 8, 10 Using array_filter(): Even values: 2, 4, 6, 8, 10
PHP provides many array functions that can replace loops with break/continue statements, often resulting in more concise and readable code.
Using Early Returns in Functions
<?php
// Using break/continue in a function
function validateUserWithLoops($userData) {
$errors = [];
$requiredFields = ['name', 'email', 'password'];
foreach ($requiredFields as $field) {
if (!isset($userData[$field]) || empty($userData[$field])) {
$errors[] = "Missing required field: $field";
continue;
}
// Field-specific validation
switch ($field) {
case 'email':
if (!filter_var($userData['email'], FILTER_VALIDATE_EMAIL)) {
$errors[] = "Invalid email format";
}
break;
case 'password':
if (strlen($userData['password']) < 8) {
$errors[] = "Password must be at least 8 characters";
}
break;
}
}
return empty($errors) ? true : $errors;
}
// Using early returns instead
function validateUserWithEarlyReturns($userData) {
$requiredFields = ['name', 'email', 'password'];
$errors = [];
// Check required fields first
foreach ($requiredFields as $field) {
if (!isset($userData[$field]) || empty($userData[$field])) {
$errors[] = "Missing required field: $field";
}
}
// Return early if required fields are missing
if (!empty($errors)) {
return $errors;
}
// Email validation
if (!filter_var($userData['email'], FILTER_VALIDATE_EMAIL)) {
$errors[] = "Invalid email format";
}
// Password validation
if (strlen($userData['password']) < 8) {
$errors[] = "Password must be at least 8 characters";
}
return empty($errors) ? true : $errors;
}
// Test both functions
$user1 = [
'name' => 'John Doe',
'email' => 'john@example.com',
'password' => 'short'
];
$result1 = validateUserWithLoops($user1);
$result2 = validateUserWithEarlyReturns($user1);
echo "Result with loops: ";
print_r($result1);
echo "<br>";
echo "Result with early returns: ";
print_r($result2);
?>
Output:
Result with loops: Array ( [0] => Password must be at least 8 characters ) Result with early returns: Array ( [0] => Password must be at least 8 characters )
Using early returns in functions can often lead to more readable code than using break/continue statements in complex nested structures. This approach makes the control flow more explicit and easier to follow.
Practice Exercises
Exercise 1: Finding Prime Numbers
Create a function that finds all prime numbers up to a given limit using break and continue statements to optimize the process.
<?php
// Start with this code template
function findPrimes($limit) {
$primes = [];
// Loop through numbers from 2 to $limit
for ($num = 2; $num <= $limit; $num++) {
// Check if $num is prime
// Use break to optimize when a factor is found
// Use continue for optimization when appropriate
}
return $primes;
}
// Test the function
$limit = 50;
$primes = findPrimes($limit);
echo "Prime numbers up to $limit: " . implode(", ", $primes);
?>
Hint:
A number is prime if it's only divisible by 1 and itself. You can use a break statement to exit the checking loop as soon as you find a factor (which proves the number is not prime). You can also use continue to skip known non-prime numbers (like even numbers greater than 2).
Exercise 2: Data Processing with Error Handling
Create a function that processes a list of transactions, validating each one and using break/continue to handle errors according to their severity.
<?php
// Start with this code template
$transactions = [
['id' => 101, 'amount' => 150.00, 'status' => 'pending'],
['id' => 102, 'amount' => -50.00, 'status' => 'completed'], // Invalid amount
['id' => 103, 'amount' => 75.25, 'status' => 'completed'],
['id' => 104, 'amount' => 200.00, 'status' => 'unknown'], // Invalid status
['id' => 105, 'amount' => 0.00, 'status' => 'pending'], // Zero amount
];
function processTransactions($transactions) {
$results = [
'processed' => 0,
'skipped' => 0,
'processing_halted' => false,
'total_amount' => 0,
];
// Process each transaction
// Use continue for non-critical errors
// Use break for critical errors
return $results;
}
// Test the function
$results = processTransactions($transactions);
print_r($results);
?>
Hint:
Use continue to skip transactions with minor issues (like zero amount) and break to halt processing entirely on critical issues (like negative amounts). Keep track of statistics like the number of transactions processed and skipped.
Exercise 3: Matrix Operations
Create a function that performs operations on a matrix (2D array) using nested loops with break and continue to handle special cases.
<?php
// Start with this code template
$matrix = [
[1, 2, 0, 4],
[5, 0, 7, 8],
[0, 10, 11, 12],
[13, 14, 15, 0]
];
function processMatrix($matrix) {
$result = [
'row_sums' => [],
'col_sums' => [],
'zero_positions' => [],
'max_value' => 0,
'max_position' => []
];
// Process the matrix
// Calculate row sums (skip rows with more than one zero)
// Calculate column sums (skip cells with zero value)
// Find positions of all zeros
// Find the maximum value and its position
return $result;
}
// Test the function
$result = processMatrix($matrix);
print_r($result);
?>
Hint:
Use nested loops to traverse the matrix. Use continue to skip specific cells (like zeros) when calculating sums. Use break to skip entire rows when they contain too many zeros. Keep track of the maximum value and its position while traversing.
Homework Assignment
Create a program that uses break and continue statements
Develop a PHP application that demonstrates the use of break and continue statements in at least three different scenarios:
- Create a data validation system that validates a set of records (like user registrations), using continue to skip invalid records and break to halt processing on critical errors.
- Implement a search algorithm that searches for specific patterns in text, using break to optimize performance when matches are found.
- Develop a simulated data processing pipeline that handles different types of data items, using both break and continue to manage the flow control based on item properties.
Requirements:
- Use both break and continue statements appropriately in each scenario.
- Include at least one example of nested loops with break/continue with a numeric argument.
- Implement error handling and logging to demonstrate the effects of the control statements.
- Include meaningful comments explaining your code and the logic behind your break/continue usage.
- Format your output with appropriate HTML and CSS.
- Submit your code via the class GitHub repository by the next session.