Skip to content
Learn Netverks

Lesson

Step 11/36 31% through track

loops

Loops: while, for, foreach

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

This lesson

This lesson teaches Loops: while, for, foreach: the syntax, APIs, and habits you need before advancing in PHP.

Frameworks like Laravel are OOP-first—classes, visibility, and inheritance show up in every code review.

You will apply Loops: while, for, foreach 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.

Loops repeat work. foreach is the workhorse for arrays; while and for suit counters and conditions.

foreach

foreach ($items as $item) {
    echo $item . "\n";
}

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

for and while

for ($i = 0; $i < 3; $i++) {
    echo $i . "\n";
}

$n = 3;
while ($n > 0) {
    echo $n-- . "\n";
}

break and continue

break exits the loop; continue skips to the next iteration. Label breaks exist but use sparingly.

Important interview questions and answers

  1. Q: foreach by value vs reference?
    A: foreach ($arr as &$v) modifies the original array—unset $v after to avoid accidental aliasing.
  2. Q: When avoid foreach?
    A: When you need index arithmetic without keys—for can be clearer; for generators, foreach is ideal.

Self-check

  1. Which loop is idiomatic for a plain indexed array of strings?
  2. What does continue do inside a loop?

Challenge

Sum with a loop

  1. Create an array of five integers.
  2. Use foreach to compute the sum.
  3. Echo the total.

Done when: the terminal prints the correct sum.

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

  • foreach vs for?
  • break continue when?

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