Skip to content
Learn Netverks

Lesson

Step 15/36 42% through track

foreach-iteration

Iterating with foreach patterns

Last reviewed May 28, 2026 Content v20260528
Track mode
server_script
Means
Server runner
Reading
~1 min
Level
beginner

This lesson

This lesson teaches Iterating with foreach patterns: the syntax, APIs, and habits you need before advancing in PHP.

Teams ship Iterating with foreach patterns on every PHP codebase—skipping it leaves gaps in debugging and code reviews.

You will apply Iterating with foreach patterns in contexts like: LAMP/LEMP stacks, Laravel apps, WordPress themes/plugins, and shared hosting.

Write PHP in the editor and click Run on server—the dev runner executes your script and returns stdout/stderr (set LEARNING_RUNNER_ENABLED=true locally).

When you can explain the previous lesson's ideas without copying starter code.

foreach is the idiomatic way to walk arrays. Master value-only, key-value, and by-reference patterns to avoid subtle bugs.

Key-value iteration

foreach ($config as $key => $value) {
    echo "{$key} = {$value}\n";
}

Modifying by reference

foreach ($items as &$item) {
    $item = strtoupper($item);
}
unset($item); // break the reference

Iterating copies

foreach ($arr as $value) copies scalars by value; objects are object handles—mutations visible unless you clone.

Self-check

  1. Why unset($item) after a reference loop?
  2. Can you modify keys during foreach?

Interview tip Lesson completion confidence

Can you explain this lesson in 30 seconds without reading notes?

Not saved yet.

Playground

Runs on the configured server runner (dev: npm run runner with LEARNING_RUNNER_ENABLED=true). Output appears below the editor.

Check yourself

Multiple choice — immediate feedback.

Discussion

Past discussion is visible to everyone. Only logged-in users can post comments and replies.

Starter discussion topics

  • & reference trap?
  • Key value unpack?

Sign up or log in to post comments and sync lesson progress across devices.

No discussion yet. Be the first to ask a question.

Jump