Loops in PHP
Loops allow you to execute a block of code repeatedly, which is essential for processing collections of data, automating repetitive tasks, and building dynamic applications.
The while Loop
The while loop executes a block of code as long as the specified condition is true:
<?php
$counter = 1;
while ($counter <= 5) {
echo "Count: $counter<br>";
$counter++;
}
// Output:
// Count: 1
// Count: 2
// Count: 3
// Count: 4
// Count: 5
?>
Warning: Always ensure the loop condition will eventually become false. Forgetting to increment or modify the counter will create an infinite loop that can crash your application.
The do...while Loop
The do...while loop executes the code block at least once before checking the condition:
<?php
$counter = 1;
do {
echo "Count: $counter<br>";
$counter++;
} while ($counter <= 5);
// Even if condition is false initially, code runs once:
$x = 10;
do {
echo "This runs once even though x is not < 10";
} while ($x < 10);
?>
Note: Use do...while when you need the code to execute at least once before checking the condition, such as validating user input.
The for Loop
The for loop is ideal when you know how many times you want to iterate:
<?php
// Syntax: for (initialization; condition; increment)
for ($i = 1; $i <= 5; $i++) {
echo "Iteration: $i<br>";
}
// Multiple initializations and increments:
for ($i = 0, $j = 10; $i < 5; $i++, $j--) {
echo "i: $i, j: $j<br>";
}
// Descending loop:
for ($i = 10; $i > 0; $i--) {
echo "Countdown: $i<br>";
}
?>
The foreach Loop
The foreach loop is specifically designed for iterating over arrays and is the most commonly used loop in PHP:
<?php
// Simple array iteration:
$fruits = ["Apple", "Banana", "Cherry"];
foreach ($fruits as $fruit) {
echo "$fruit<br>";
}
// Associative array with keys and values:
$person = [
"name" => "John",
"age" => 30,
"city" => "New York"
];
foreach ($person as $key => $value) {
echo "$key: $value<br>";
}
?>
Tip: Always use foreach when working with arrays. It's cleaner, safer, and more readable than using traditional for loops with array indices.
Modifying Array Elements in foreach
You can modify array elements by using a reference (&) in the foreach loop:
<?php
$numbers = [1, 2, 3, 4, 5];
// Using reference to modify original array:
foreach ($numbers as &$number) {
$number = $number * 2;
}
unset($number); // Always unset the reference after the loop
print_r($numbers); // [2, 4, 6, 8, 10]
?>
Warning: Always unset() the reference variable after a foreach loop. The reference remains active and can cause unexpected behavior in subsequent code.
Loop Control Statements
The break Statement
The break statement exits the loop immediately:
<?php
// Exit loop when condition is met:
for ($i = 1; $i <= 10; $i++) {
if ($i == 5) {
break; // Exit the loop
}
echo "$i ";
}
// Output: 1 2 3 4
// Break from nested loops with level:
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) ";
}
}
?>
The continue Statement
The continue statement skips the current iteration and moves to the next one:
<?php
// Skip even numbers:
for ($i = 1; $i <= 10; $i++) {
if ($i % 2 == 0) {
continue; // Skip to next iteration
}
echo "$i ";
}
// Output: 1 3 5 7 9
// Skip specific values in foreach:
$fruits = ["Apple", "Banana", "Cherry", "Date"];
foreach ($fruits as $fruit) {
if ($fruit == "Banana") {
continue; // Skip Banana
}
echo "$fruit ";
}
// Output: Apple Cherry Date
?>
Nested Loops
Loops can be nested inside other loops to work with multi-dimensional data:
<?php
// Multiplication table:
for ($i = 1; $i <= 5; $i++) {
for ($j = 1; $j <= 5; $j++) {
$result = $i * $j;
echo "$result\t";
}
echo "<br>";
}
// Nested foreach for 2D array:
$students = [
["name" => "John", "grade" => 85],
["name" => "Jane", "grade" => 92],
["name" => "Bob", "grade" => 78]
];
foreach ($students as $student) {
foreach ($student as $key => $value) {
echo "$key: $value ";
}
echo "<br>";
}
?>
Note: Be cautious with nested loops as they can significantly impact performance. A loop inside a loop that each run 1000 times results in 1,000,000 iterations.
Alternative Syntax for Loops
PHP provides alternative syntax for loops that is useful in templates:
<?php
// Traditional syntax:
for ($i = 1; $i <= 5; $i++) {
echo "<li>Item $i</li>";
}
// Alternative syntax (better for mixing HTML):
for ($i = 1; $i <= 5; $i++):
echo "<li>Item $i</li>";
endfor;
// Alternative foreach syntax:
foreach ($fruits as $fruit):
echo "<li>$fruit</li>";
endforeach;
// Alternative while syntax:
while ($condition):
// code
endwhile;
?>
Practical Examples
Generating HTML Lists
<?php
$tasks = ["Buy groceries", "Clean house", "Finish project"];
echo "<ul>";
foreach ($tasks as $index => $task) {
$number = $index + 1;
echo "<li>Task $number: $task</li>";
}
echo "</ul>";
?>
Processing Form Data
<?php
// Assume $_POST contains multiple checkboxes:
$selectedItems = $_POST['items'] ?? [];
foreach ($selectedItems as $item) {
echo "Processing: $item<br>";
}
// Validate multiple inputs:
$errors = [];
$fields = ['name', 'email', 'phone'];
foreach ($fields as $field) {
if (empty($_POST[$field])) {
$errors[] = ucfirst($field) . " is required";
}
}
?>
Building a Pagination System
<?php
$totalPages = 10;
$currentPage = 5;
echo "<div class='pagination'>";
for ($i = 1; $i <= $totalPages; $i++) {
if ($i == $currentPage) {
echo "<span class='active'>$i</span> ";
} else {
echo "<a href='?page=$i'>$i</a> ";
}
}
echo "</div>";
?>
Loop Performance Tips
<?php
// BAD: Calculating count in each iteration:
for ($i = 0; $i < count($array); $i++) {
// code
}
// GOOD: Calculate count once:
$count = count($array);
for ($i = 0; $i < $count; $i++) {
// code
}
// BEST: Use foreach for arrays:
foreach ($array as $item) {
// code
}
// Avoid nested database queries:
// BAD:
foreach ($users as $user) {
$orders = getOrdersForUser($user['id']); // Query in loop!
}
// GOOD:
$allOrders = getAllOrdersWithUsers(); // Single query
?>
Tip: When working with databases, try to fetch all required data in a single query rather than querying inside a loop. This dramatically improves performance.
Infinite Loops and Their Uses
<?php
// Intentional infinite loop (useful for daemons/background processes):
while (true) {
// Process tasks
$task = getNextTask();
if ($task === null) {
break; // Exit when no more tasks
}
processTask($task);
sleep(1); // Prevent CPU overload
}
// Alternative infinite loop:
for (;;) {
// Continues forever unless break is called
}
?>
Practice Exercise
Task: Create a number guessing game simulator:
- Set a secret number between 1 and 100
- Use a loop to simulate guesses from 1 to 100
- For each guess, display "Too low" or "Too high"
- When found, display "Found in X attempts" and exit
- Bonus: Implement a binary search algorithm instead of sequential guessing
- Extra: Create an array of 20 products and use foreach to display them in an HTML table with alternating row colors
Best Practices
- Use
foreach for arrays whenever possible - it's cleaner and safer
- Always ensure loops have an exit condition to prevent infinite loops
- Unset reference variables after foreach loops with references
- Avoid performing expensive operations (database queries, file operations) inside loops
- Use
break to exit early when you find what you're looking for
- Use
continue to skip unnecessary processing
- Cache array counts and function results outside loops
- Consider using array functions (array_map, array_filter) as alternatives to loops