Topics Covered in This PHP & MySQL Tutorial:
While Loops, Do…while Loops, for Loops, Foreach Loops, Breaking Out of a Loop, Continue Statements
Exercise Overview
Loops form the backbone of efficient programming logic, enabling you to execute repetitive tasks without redundant code. As a PHP developer, mastering loop structures is essential for building scalable applications. This comprehensive tutorial explores PHP's diverse loop implementations, from basic while loops to sophisticated foreach iterations over complex data structures.
This tutorial uses practical shopping scenarios to demonstrate loop concepts. Each loop type is explored through hands-on coding exercises with immediate browser testing to see results.
While Loops
The while loop represents one of the most fundamental control structures in programming. Its elegance lies in its simplicity: while a specified condition remains true, execute the enclosed code block. Consider this real-world analogy:
while (I have more than $1) {
Keep shopping!
}
This statement continues the shopping spree as long as funds exceed one dollar. While perhaps not the most prudent financial strategy, it perfectly illustrates the while loop's conditional execution pattern.
In your code editor, open loops.php from the phpclass folder.
Now let's implement a practical while loop in PHP. Between the
<body>tags, add the following code:<?php $money = 100; while ($money > 1) {—$money; echo "I just bought something! I have $money dollars left now.<br>"; } ?>Let's break down the mechanics:
- We initialize
$moneyto 100, representing our starting budget. - The while condition checks if
$moneyexceeds 1 before each iteration. —$moneydecrements our balance by 1, simulating a purchase.- The echo statement outputs our remaining balance. Note how the
$moneyvariable interpolates directly within double quotes. - The
<br>tag creates visual separation between each transaction line.
- We initialize
Save the file and navigate to it in your browser:
- Mac: localhost:8888/phpclass/loops.php
- Windows: localhost/phpclass/loops.php
You'll witness an impressive shopping spree! Notice how the loop begins execution immediately, so our first output shows 99 dollars remaining.
Return to your code editor to explore edge cases.
What happens when our initial condition isn't met? Modify the
$moneyvariable to 1:$money = 1; while ($money > 1) {—$money; echo "I just bought something! I have $money dollars left now.<br>"; }Save and refresh your browser:
- Mac: localhost:8888/phpclass/loops.php
- Windows: localhost/phpclass/loops.php
The page displays nothing because our condition fails from the start. Since 1 is not greater than 1, the loop body never executes—demonstrating the while loop's pre-condition testing behavior.
While Loop Implementation
Initialize Variable
Set the starting value for your loop condition variable, such as $money = 100
Define Condition
Specify the condition that must remain true for the loop to continue executing
Modify Variable
Include code within the loop that changes the condition variable to eventually end the loop
While loops only execute if the initial condition is true. If you start with $money = 1 and check $money > 1, the loop will never run.
Do…while Loops
The do…while loop addresses a common programming scenario: ensuring code execution at least once before evaluating continuation criteria. This structure proves invaluable when you need guaranteed initial execution, such as prompting user input or performing setup operations. The syntax inverts the traditional while pattern:
do {
do something
} while (you can keep doing it again if this is true)
Return to your code editor to implement this pattern.
Replace everything between the
<?php ?>tags with:$money = 1; do {—$money; echo "I just bought something! I have $money dollars left now.<br>"; } while ($money > 1);Save and refresh your browser:
- Mac: localhost:8888/phpclass/loops.php
- Windows: localhost/phpclass/loops.php
Now you see one purchase transaction! The do block executes unconditionally first, then evaluates the while condition for subsequent iterations.
While Loop Implementation
Initialize Variable
Set the starting value for your loop condition variable, such as $money = 100
Define Condition
Specify the condition that must remain true for the loop to continue executing
Modify Variable
Include code within the loop that changes the condition variable to eventually end the loop
While loops only execute if the initial condition is true. If you start with $money = 1 and check $money > 1, the loop will never run.
For Loops
The for loop provides the most comprehensive iteration control, consolidating initialization, condition testing, and increment operations into a single, readable statement. This makes it particularly effective for counter-based iterations and situations requiring precise loop control. The syntax follows this pattern:
for (expression 1; expression 2; expression 3) {
do something
}
- Expression 1 executes once at loop initialization.
- Expression 2 evaluates before each iteration; if true, the loop continues.
- Expression 3 executes after each iteration, typically updating the loop variable.
Return to your code editor to implement a for loop.
Replace the content between the
<?php ?>tags:for ($money = 100; $money > 1;—$money) { echo "I have $money dollars, so I can still shop!<br>"; }This concise structure accomplishes the same result as our earlier while loop:
- The first expression initializes
$moneyto 100. - The second expression continues the loop while $money exceeds 1.
- The third expression decrements $money after each iteration.
Notice how the for loop encapsulates all loop control logic in one line, separated by semicolons. This makes it ideal for situations where you know the exact iteration parameters upfront.
- The first expression initializes
Save and test your implementation:
- Mac: localhost:8888/phpclass/loops.php
- Windows: localhost/phpclass/loops.php
You'll observe the familiar countdown from 100, demonstrating how for loops can elegantly replace while loops when you need structured iteration control.
For Loop Structure
Expression 1
Initialization - runs once at the beginning to set up loop variables and starting conditions.
Expression 2
Condition - evaluated before each iteration to determine if the loop should continue running.
Expression 3
Increment/Decrement - executed at the end of each loop iteration to modify the loop variable.
Remember that the three expressions in a for loop must be separated by semicolons, not commas. This is a common syntax error for beginners.
Foreach Loops
The foreach loop represents PHP's most elegant solution for array traversal, eliminating the need for manual index management while providing intuitive access to array elements. Modern PHP development heavily relies on foreach loops for processing collections, API responses, and database result sets. The fundamental syntax is:
foreach (someArray as someTemporaryValue) {
do something, most typically you would output someTemporaryValue
}
During each iteration, PHP automatically assigns the current array element to your specified temporary variable, enabling clean, readable code that focuses on data processing rather than array mechanics.
Open foreach.php from the phpclass folder to explore pre-built data structures.
Examine the three distinct array types we've prepared:
$movies: An indexed array containing popular film titles.$customer: An associative array with customer profile data.$cars: A multidimensional array containing detailed vehicle specifications.
These examples represent common real-world data structures you'll encounter in PHP applications, from simple lists to complex nested objects.
Navigate to approximately line 77 and create new
<?php ?>tags below the existing closing tag. This separation helps distinguish your code from the provided data structures.Let's begin with the indexed array. Add this foreach implementation:
foreach ($movies as $value) { echo $value; echo '<br>'; }This code iterates through
$movies, assigning each film title to$value(you can use any variable name you prefer). We then output each title with a line break for readability.Test your movie list:
- Mac: localhost:8888/phpclass/foreach.php
- Windows: localhost/phpclass/foreach.php
You'll see a clean, formatted list of all movie titles.
Now let's process associative array data. Modify your foreach to target the customer array:
foreach ($customer as $value) { echo $value; echo '<br>'; }Refresh your browser to see the customer data values displayed.
To include both keys and values (essential for associative arrays), we'll implement the key-value pair syntax:
Often, you'll want to display both the field names and their values, creating output like:
firstName: Jeremy
lastName: KayThis requires accessing both the key names and their associated values using the
$key => $valuepattern.Update your foreach loop:
foreach ($customer as $key => $value) { echo "$key: $value"; echo '<br>'; }The
$keyvariable now contains each associative array key, while$valueholds the corresponding data.View the enhanced output showing both field labels and values in a professional format.
For complex data structures like our multidimensional car array, we need nested foreach loops. Let's explore this powerful technique.
Examine the
$carsarray structure. It contains multiple vehicle records, each with detailed specifications—essentially an array containing multiple associative arrays.Replace your foreach loop with this initial attempt:
foreach ($cars as $i) { echo $i; }Refresh your browser and observe the output:
Notice: Array to string conversion in …/htdocs/phpclass/foreach.php on line 80 Array
This notice occurs because we're attempting to echo an array directly. Each
$icontains a complete car record (an associative array), which PHP can't directly convert to a string. We need to iterate through each individual car's data.Implement nested foreach loops for proper multidimensional array handling:
foreach ($cars as $i) { foreach ($i as $key => $value) { echo "$key: $value"; } }The outer loop processes each car record, while the inner loop handles the individual specifications within each record.
The output works but lacks formatting. Let's add HTML structure for better presentation:
foreach ($cars as $i) { echo '<p>'; foreach ($i as $key => $value) { echo "$key: $value"; echo '<br>'; } echo '</p>'; }This wraps each car's information in paragraph tags and separates individual specifications with line breaks, creating a professional, readable format.
View the final result—a well-organized display of all vehicle data that would be perfect for a car inventory system or API response formatting.
Array Processing with Foreach
Simple Array Iteration
Use foreach($array as $value) to loop through indexed arrays and access each element
Key-Value Pairs
Use foreach($array as $key => $value) to access both array keys and values in associative arrays
Multidimensional Arrays
Nest foreach loops to iterate through arrays containing other arrays as elements
Array Types Handled
Indexed Arrays
Simple arrays with numeric indices. Foreach automatically handles the indexing for easy element access.
Associative Arrays
Arrays with named keys. Access both key names and values using key-value pair syntax.
Multidimensional Arrays
Arrays containing other arrays. Use nested foreach loops to access all levels of data.
Breaking Out of the Loop
Professional applications often require premature loop termination based on specific conditions—perhaps you've found the target data, encountered an error, or reached a processing limit. The break statement provides clean loop exit functionality, immediately transferring control to the code following the loop structure.
Open break.php from the phpclass folder.
Create a countdown loop to demonstrate break functionality. Add this code between the
<body>tags:<?php for ($count = 50; $count > 1;—$count) { echo "$count <br>"; } ?>This for loop initializes
$countat 50, continues while$countexceeds 1, and decrements after each iteration.Test the basic countdown functionality:
- Mac: localhost:8888/phpclass/break.php
- Windows: localhost/phpclass/break.php
Now implement conditional loop termination. Add break logic to halt execution at 25:
for ($count = 50; $count > 1;—$count) { echo "$count <br>"; if ($count == 25) { break; } }When
$countreaches exactly 25, the break statement immediately exits the loop, regardless of the original loop condition.Refresh your browser to confirm the loop terminates precisely at 25, demonstrating how break provides programmatic control over loop execution beyond the initial conditional parameters.
The break command immediately stops loop execution and exits the loop entirely. Use it when you need to terminate a loop based on a specific condition being met.
Implementing Break Conditions
Add Conditional Check
Use an if statement within the loop to test for your break condition
Execute Break
When the condition is met, execute the break statement to immediately exit the loop
Continue Statements
While break terminates the entire loop, the continue statement offers more nuanced control by skipping only the current iteration and proceeding to the next cycle. This proves invaluable for filtering operations, error handling, and conditional processing within loops. Instead of nested if-else structures, continue statements create cleaner, more readable code.
Let's implement a practical example: displaying only even numbers from our countdown.
First, remove the break logic to restore the basic loop:
for ($count = 50; $count > 1;—$count) { echo "$count <br>"; }Now implement even number filtering using the modulus operator. The % (modulus) operator returns the remainder after division—even numbers divided by 2 yield remainder 0, while odd numbers yield remainder 1:
for ($count = 50; $count > 1;—$count) { if ($count % 2 == 1) { continue; } echo "$count <br>"; }When the condition detects an odd number (remainder equals 1), continue skips the echo statement and jumps to the next iteration. Even numbers pass through to display normally.
Test your filtered output:
- Mac: localhost:8888/phpclass/break.php
- Windows: localhost/phpclass/break.php
You'll see a clean list containing only even numbers, demonstrating how continue enables elegant data filtering within loop structures.
Close your files—you've successfully mastered PHP's complete loop ecosystem, from basic while loops to sophisticated continue logic that will serve you well in real-world application development.
Break vs Continue
| Feature | Break Statement | Continue Statement |
|---|---|---|
| Effect | Exits entire loop | Skips current iteration only |
| Loop Status | Loop terminates | Loop continues with next iteration |
| Use Case | Stop processing completely | Skip specific conditions |
The modulus operator (%) returns the remainder after division. Even numbers divided by 2 have remainder 0, odd numbers have remainder 1.