while, do-while, for, & foreachLoops repeat a block of code as long as a specified condition remains true. PHP supports 4 primary loop types suited for numeric iterations, condition-driven loops, and array traversals.
flowchart TD
A["Choose Loop Type"] --> B{"Is Iterating Over Array / Collection?"}
B -- Yes --> C["foreach ($items as $key => $val)"]
B -- No --> D{"Known Fixed Iteration Count?"}
D -- Yes --> E["for ($i = 0; $i < $count; $i++)"]
D -- No --> F{"Execute At Least Once?"}
F -- Yes --> G["do { ... } while (condition);"]
F -- No --> H["while (condition) { ... }"]
break & continuebreak: Exits loop immediately.continue: Skips current iteration step and proceeds to next iteration loop evaluation.<?php
declare(strict_types=1);
// 1. foreach Loop with Key & Value
$userRoles = [
'maksudur' => 'Administrator',
'sarah' => 'Senior Developer',
'john' => 'Project Manager'
];
echo "--- User Role Directory ---
";
foreach ($userRoles as $username => $role) {
echo "User: " . ucfirst($username) . " | Role: " . $role . "
";
}
// 2. for Loop with step and break/continue logic
echo "
--- Evens Only (Break at 8) ---
";
for ($i = 1; $i <= 10; $i++) {
if ($i % 2 !== 0) {
continue; // Skip odd numbers
}
if ($i == 8) {
break; // Interrupt loop at 8
}
echo "Even Count: $i
";
}
// 3. while Loop for Process Polling
$attempts = 0;
while ($attempts < 3) {
$attempts++;
echo "Attempting Connection #$attempts...
";
}
foreach for All Array Iterations: foreach is optimized, readable, and prevents array out-of-bounds indexing errors.foreach Without Reference: Use foreach ($array as &$value) if mutating values directly, and call unset($value) immediately after.for Loop Headers: Write $len = count($arr); for ($i=0; $i < $len; $i++) instead of calling count() on every iteration step.Write a foreach loop over an associative array $prices = ['laptop' => 1200, 'mouse' => 25, 'desk' => 300] that prints items costing more than $50!
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.
You've completed this section! Take a quick 5-question quiz to check your understanding.