Learn how to use loops in PHP to iterate through values, process arrays, and perform repeated actions easily and efficiently.
π What Are Loops in PHP?
Loops allow you to execute a block of code multiple times. They're essential when working with arrays, repetitive tasks, and dynamic content.
In PHP, the three most common loop types are:
forwhileforeach
π The for Loop
The for loop is ideal when you know how many times to iterate.
<?php for ($i = 1; $i <= 5; $i++) { echo "Number: $i <br>"; } ?> This prints numbers from 1 to 5. It includes:
- Initialization:
$i = 1 - Condition:
$i <= 5 - Increment:
$i++
π The while Loop
Use while when the number of iterations isnβt fixed upfront.
<?php $count = 1; while ($count <= 3) { echo "Count: $count <br>"; $count++; } ?> The loop runs as long as $count is less than or equal to 3.
β‘οΈ The do...while Loop
Unlike while, the do...while loop executes the block at least once.
<?php $start = 1; do { echo "Start: $start <br>"; $start++; } while ($start <= 2); ?> It will always run once, even if the condition fails afterward.
π The foreach Loop
foreach is perfect for looping through arrays or collections.
<?php $colors = ["red", "green", "blue"]; foreach ($colors as $color) { echo "Color: $color <br>"; } ?> Want both key and value?
<?php $person = ["name" => "John", "age" => 30]; foreach ($person as $key => $value) { echo "$key: $value <br>"; } ?> π§© Nested Loops
You can use loops inside loops. Here's a multiplication table example:
<?php for ($i = 1; $i <= 3; $i++) { for ($j = 1; $j <= 3; $j++) { echo "$i x $j = " . ($i * $j) . " <br>"; } } ?> π¦ Using break and continue
break exits the loop immediately, while continue skips to the next iteration.
<?php for ($i = 1; $i <= 5; $i++) { if ($i == 3) continue; if ($i == 5) break; echo "Loop: $i <br>"; } ?> π Real-World Examples
- Looping through database query results
- Generating HTML tables or dropdown options
- Validating multiple form fields
- Paginating records
β Best Practices
- Use
foreachfor arrays,forfor indexed iterations - Donβt forget to increment counters
- Avoid infinite loops , always validate your condition
- Keep nesting minimal for readability
Tags: PHP loops, foreach PHP, for loop PHP, while loop PHP, beginner PHP tutorial
π Coming next: Learn how to define and use functions in PHP effectively.