Beginner-Friendly Topic
Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on.You've got this!
Lesson 5 of 9
Loops - for, while, foreach & Array Iteration
PHP provides four loop constructs - each suited to different scenarios. foreach is the most common for PHP arrays. Understanding break, continue, and nested loops equips you for real data processing tasks like rendering blog post lists, processing CSV rows, and paginating database results.
All Loop Types with Real Examples
<?php
declare(strict_types=1);
// ── for - when you know iteration count ─────────────────────────
for ($i = 1; $i <= 5; $i++) {
echo "Page $i | "; // Page 1 | Page 2 | ...
}
// ── while - when you loop until a condition ──────────────────────
$buffer = "";
$handle = fopen("posts.txt", "r");
while (!feof($handle)) {
$buffer .= fgets($handle); // read line by line
}
fclose($handle);
// ── do-while - executes at least once ───────────────────────────
$retries = 0;
do {
$success = attemptDatabaseConnection();
$retries++;
} while (!$success && $retries < 3);
// ── foreach - the PHP workhorse ──────────────────────────────────
$posts = [
["id" => 1, "title" => "Getting Started with PHP", "views" => 1200],
["id" => 2, "title" => "PDO Deep Dive", "views" => 800],
["id" => 3, "title" => "Security in PHP", "views" => 2400],
];
// Iterate values
foreach ($posts as $post) {
echo "{$post['title']} ({$post['views']} views)
";
}
// Iterate key => value
foreach ($posts as $index => $post) {
echo "$index: {$post['title']}
";
}
// Modify by reference
foreach ($posts as &$post) {
$post["views"] += 100; // add 100 views to each post
}
unset($post); // IMPORTANT: unset reference to prevent bugs
// ── break and continue ───────────────────────────────────────────
foreach ($posts as $post) {
if ($post["views"] < 1000) continue; // skip low-traffic posts
if ($post["id"] === 3) break; // stop at post 3
echo $post["title"] . "
";
}
// ── Nested foreach - e.g. categories with posts ─────────────────
$categories = [
"PHP" => ["Syntax", "OOP", "PDO"],
"Security" => ["XSS", "CSRF", "SQL Injection"],
];
foreach ($categories as $category => $topics) {
echo "=== $category ===
";
foreach ($topics as $index => $topic) {
echo " " . ($index + 1) . ". $topic
";
}
}
function attemptDatabaseConnection(): bool { return true; }Quick Quiz
Tip
Tip
Practice Loops for while foreach Array Iteration in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and concepts for Loops - for, while, foreach & Array Iteration
Practice Task
Note
Practice Task - (1) Write a working example of Loops for while foreach Array Iteration from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Common Mistake
Warning
A common mistake with Loops for while foreach Array Iteration is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready php code.
Finished this lesson?