Coding/Learn/php/php loops and iterations
PHP Foundational Course
01.Introduction, Server-Side Architecture & Syntax
02.Variables, Strict Types & Dynamic Casting
03.Strings, Numbers & Built-in Math Functions
04.Operators, Null Coalescing & Magic Constants
05.Control Flow: If-Else, Switch & Modern Match Expressions
06.Loops: While, For & Foreach Traversal
07.Functions, Type Declarations & Named Arguments
08.Arrays & Functional Array Manipulation
09.Superglobals, Form Handling & Input Sanitization
10.Date, Time & DateTimeImmutable Objects
11.File System, Streams & I/O Operations
12.Cookies, Sessions & State Management
13.Exceptions, Throwables & Custom Error Fences
14.Classes, Objects & Constructor Property Promotion
15.Inheritance, Access Modifiers & Method Overriding
16.Interfaces, Abstract Classes & Polymorphism
17.Traits, Static Members & Namespaces
18.PDO, MySQL & Prepared Statements against SQL Injection
19.JSON & XML REST API Interoperability
20.Capstone: Production Secure Backend API & User Registry Engine
Course Certificate0%

Complete all lessons to earn

LearnLoops: While, For & Foreach Traversal
6 / 20 0%
Lesson 06 of 20
8 mins read

Loops: While, For & Foreach Traversal

PreviousNext Lesson
In Plain English

Loops allow automated repetitive execution. Learn while, do-while, for counters, break/continue control, and the powerhouse foreach loop designed specifically for iterating over indexed arrays and key-value hash maps.

The Mental Model

"A for loop is an odometer ticking off exact mile markers from 1 to 10. A foreach loop is an automated postal worker picking up every single letter in a delivery bag one by one until the bag is empty."

Deep Dive: How It Works

The foreach Loop: foreach ($items as $item) or foreach ($map as $key => $val) traverses any iterable.

By-Reference Iteration: foreach ($items as &$val) allows direct modification of elements in place (remember to unset($val) after loop!).

Jump Statements: break stops loop execution; continue skips immediately to the next iteration.

Syntax Blueprint

<?php

foreach ($users as $id => $name) {
    echo "ID: {$id} => {$name}\n";
}

Use foreach with $key => $value syntax to traverse array elements smoothly.

PointCore Rules to Remember

Point star
Foreach Efficiency: foreach is the standard, most idiomatic way to iterate over arrays and iterables in PHP.
Point star
Break Levels: PHP supports break 2; and continue 2; to break out of multiple nested loop levels.
Point star
Array Copy Behavior: By default, foreach operates on a copy of the array array pointer.

Common Beginner Traps & How to Fix Them

Mistake:Leaving a reference variable bound after a foreach ($arr as &$v) loop.

Why it happens: $v remains bound to the last element of $arr; subsequent assignments to $v will accidentally overwrite the last element.

How to fix: Always call unset($v) immediately following by-reference foreach loops.

Pro Tip: Prefer foreach over for ($i=0; $i<count($arr); $i++) because count() inside the loop header causes O(N^2) evaluation overhead.

Live Interactive Example

Hit Run Code to see it live
Iterating Key-Value Configuration with Foreach
PHP 8.2 / CLI
1
2
3
4
5
6
7
8
9
10
11
12
Output Console
Click "Run Code" to view the rendered output.
How it works: foreach smoothly unpacked both the string keys ($name) and integer values ($port).

Your Turn: Micro Challenge

No pressure! Edit the starter code below and test your solution with instant feedback.

Micro Exercise

Filter Even Numbers with Foreach

  • PointDeclare an array $numbers = [1, 2, 3, 4, 5, 6].
  • PointIterate using foreach and print each even number on a new line preceded by "Even: ".
1
2
3
4
5
6
Sandbox Output
Click "Run & Check" to test your solution.

Finished reading and practicing?

Mark this lesson as completed to update your course progress.

PreviousNext Lesson
Overview100 SheetLearnCertificates