Skip to main content
March 23, 2026Noble Desktop Publishing Team/9 min read

Loops: Free PHP & MySQL Tutorial

Master PHP Loop Structures with Hands-On Examples

Loop Types Overview

While Loops

Execute code repeatedly while a condition remains true. Simple conditional repetition for basic iteration needs.

For Loops

Structured loops with initialization, condition, and increment in one statement. Perfect for counting operations.

Foreach Loops

Specialized for arrays and objects. Automatically iterates through all elements without manual indexing.

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.

Learning Approach

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.

  1. In your code editor, open loops.php from the phpclass folder.

  2. 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 $money to 100, representing our starting budget.
    • The while condition checks if $money exceeds 1 before each iteration.
    • —$money decrements our balance by 1, simulating a purchase.
    • The echo statement outputs our remaining balance. Note how the $money variable interpolates directly within double quotes.
    • The <br> tag creates visual separation between each transaction line.
  3. 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.

  4. Return to your code editor to explore edge cases.

  5. What happens when our initial condition isn't met? Modify the $money variable to 1:

    $money = 1;
    
       while ($money > 1) {—$money;
          echo "I just bought something! I have $money dollars left now.<br>";
       }
  6. 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

1

Initialize Variable

Set the starting value for your loop condition variable, such as $money = 100

2

Define Condition

Specify the condition that must remain true for the loop to continue executing

3

Modify Variable

Include code within the loop that changes the condition variable to eventually end the loop

Loop Execution Requirement

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.

While vs Do-While Loops

FeatureWhile LoopDo-While Loop
Initial ExecutionOnly if condition is trueAlways executes once
Condition CheckBefore executionAfter execution
Minimum RunsZeroOne
Recommended: Use do-while when you need guaranteed first execution regardless of initial conditions.

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)
  1. Return to your code editor to implement this pattern.

  2. 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);
  3. 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

1

Initialize Variable

Set the starting value for your loop condition variable, such as $money = 100

2

Define Condition

Specify the condition that must remain true for the loop to continue executing

3

Modify Variable

Include code within the loop that changes the condition variable to eventually end the loop

Loop Execution Requirement

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.

While vs Do-While Loops

FeatureWhile LoopDo-While Loop
Initial ExecutionOnly if condition is trueAlways executes once
Condition CheckBefore executionAfter execution
Minimum RunsZeroOne
Recommended: Use do-while when you need guaranteed first execution regardless of initial conditions.

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.
  1. Return to your code editor to implement a for loop.

  2. 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 $money to 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.

  3. 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.

Syntax Note

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.

  1. Open foreach.php from the phpclass folder to explore pre-built data structures.

  2. 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.

  3. 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.

  4. 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.

  5. 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.

  6. Now let's process associative array data. Modify your foreach to target the customer array:

    foreach ($customer as $value) {
       echo $value;
       echo '<br>';
    }
  7. Refresh your browser to see the customer data values displayed.

  8. 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: Kay

    This requires accessing both the key names and their associated values using the $key => $value pattern.

  9. Update your foreach loop:

    foreach ($customer as $key => $value) {
       echo "$key: $value";
       echo '<br>';
    }

    The $key variable now contains each associative array key, while $value holds the corresponding data.

  10. View the enhanced output showing both field labels and values in a professional format.

  11. For complex data structures like our multidimensional car array, we need nested foreach loops. Let's explore this powerful technique.

  12. Examine the $cars array structure. It contains multiple vehicle records, each with detailed specifications—essentially an array containing multiple associative arrays.

  13. Replace your foreach loop with this initial attempt:

    foreach ($cars as $i) {
       echo $i;    
    }
  14. 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 $i contains 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.

  15. 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.

  16. 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.

  17. 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

1

Simple Array Iteration

Use foreach($array as $value) to loop through indexed arrays and access each element

2

Key-Value Pairs

Use foreach($array as $key => $value) to access both array keys and values in associative arrays

3

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.

  1. Open break.php from the phpclass folder.

  2. 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 $count at 50, continues while $count exceeds 1, and decrements after each iteration.

  3. Test the basic countdown functionality:

    • Mac: localhost:8888/phpclass/break.php
    • Windows: localhost/phpclass/break.php
  4. 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 $count reaches exactly 25, the break statement immediately exits the loop, regardless of the original loop condition.

  5. 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.

Break Statement Usage

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

1

Add Conditional Check

Use an if statement within the loop to test for your break condition

2

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.

  1. Let's implement a practical example: displaying only even numbers from our countdown.

  2. First, remove the break logic to restore the basic loop:

    for ($count = 50; $count > 1;—$count) {
       echo "$count <br>";    
    }
  3. 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.

  4. 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.

  5. 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

FeatureBreak StatementContinue Statement
EffectExits entire loopSkips current iteration only
Loop StatusLoop terminatesLoop continues with next iteration
Use CaseStop processing completelySkip specific conditions
Recommended: Use continue to filter out unwanted iterations while maintaining the overall loop flow.
Modulus Operator for Even/Odd

The modulus operator (%) returns the remainder after division. Even numbers divided by 2 have remainder 0, odd numbers have remainder 1.

Key Takeaways

1While loops execute only when the initial condition is true, making them suitable for uncertain iteration counts
2Do-while loops guarantee at least one execution regardless of the initial condition state
3For loops provide a compact syntax with initialization, condition, and increment all in one statement
4Foreach loops are specifically designed for array iteration and handle indexing automatically
5Key-value pair syntax in foreach allows access to both array keys and values in associative arrays
6Break statements immediately terminate the entire loop, while continue statements skip only the current iteration
7Nested foreach loops are required to properly iterate through multidimensional arrays
8The modulus operator is useful for filtering iterations based on mathematical conditions like even/odd numbers

RELATED ARTICLES