HexLibraryHexLibrary
</> HexCodeSign inSign up
PythonJavaScriptTypeScriptCC++JavaPHPGoRustRubyBashSQLLuaPerlCOBOLPascalDelphiFortranDartSwiftC#JuliaGroovyRElixirHaskellKotlinScalaClassic ASPClipperMS-DOS
LESSONS
Introduction to PHPVariablesData TypesOperatorsStringsArraysAssociative ArraysConditions (if / else)Loops (for / foreach / while)Functions
REFERENCE
📖 Overview
🖥️ Output
📦 Variables
🔢 Numbers & Math
✍️ String
📋 Array
🔁 Condition & Loop
🧩 Function
🔄 Type & Conversion
PHP›Loops (for / foreach / while)

Loops (for / foreach / while)

Specific repetitions with for, traversing arrays with foreach, conditional repetition with while.

Simple enough for a 5-year-old to understand

for loop

Example code
1
<?php
Start.
DefinitionStart.
2
for ($i = 1; $i <= 3; $i++) {
From 1 to 3, +1 each turn.
LoopFrom 1 to 3, +1 each turn.
3
echo $i;
Write.
Output / InputWrite.
4
echo "\n";
New line.
Output / InputNew line.
5
}
End.
LoopEnd.
DefinitionLoopOutput / Input
💡 Hint: $i++ means "increment i by 1" (same as $i = $i + 1).

🎯 Exercise & Practice

Test what you've learned — answer, write code, check instantly. (1 left)

1.Print the numbers from 1 to 5 vertically using a for loop.

🎯 Expected output: 1 2 3 4 5

Loading editor…

About this topic

There are four loops in PHP: for, foreach, while, and do-while. Of these, foreach is overwhelmingly the most used in PHP code because PHP's core data structure is the array, and foreach is designed to iterate over arrays.

foreach works with both numeric and associative arrays, makes it impossible to make an index error, and can provide both the key and the value together. You must have a concrete reason to use for when iterating over an array.

Loops also have an alternative syntax for nested usage with HTML: endforeach, endfor, endwhile. This format is standard in template files.

What you will learn

  • Iterating over an array with foreach, with key and value
  • the for loop and counter logic
  • the difference between while and do-while
  • Using break and continue
  • Alternative loop syntax
  • Modifying the array by iterating with reference

When to use?

Processing database results, form fields, and API responses is almost always a foreach loop. Alternative syntax is used when generating table rows or list items.

If you want to CHANGE array elements inside a loop, you must iterate by reference; otherwise, you work on a copy and the changes are lost. Alternatively, array_map is a cleaner solution.

Common mistakes

Wrong

$nums = [1, 2, 3];
foreach ($nums as $n) {
    $n = $n * 2;
}
print_r($nums);

foreach gives a COPY of the element; modifying $n does not affect the array and it remains as is. To modify the array, you must iterate by reference or use array_map.

Correct

$nums = [1, 2, 3];
$nums = array_map(fn($n) => $n * 2, $nums);
print_r($nums);

Wrong

$i = 0;
while ($i < 3) {
    echo $i;
}

Since the counter is not incremented, the condition always remains true and the script runs until timeout. On a web server, this locks up the request and ends with a "Maximum execution time exceeded" error.

Correct

$i = 0;
while ($i < 3) {
    echo $i;
    $i++;
}

Wrong

$items = ["a", "b"];
foreach ($items as &$item) {
    $item = strtoupper($item);
}
foreach ($items as $item) {
    echo $item;
}

After the first loop, $item is still a REFERENCE to the last element; as the second loop writes to it, it corrupts the array and the last element repeats. It is mandatory to unset the variable after a reference-based foreach.

Correct

$items = ["a", "b"];
foreach ($items as &$item) {
    $item = strtoupper($item);
}
unset($item);
foreach ($items as $value) {
    echo $value;
}

Frequently asked questions

foreach or for?

If you are iterating over an array, foreach — always. You cannot make index errors, it works with associative keys too, and it shows intent clearly. for is only needed when arithmetic on the index is required or when repeating a fixed number of times.

How do I modify the array inside a loop?

By iterating with reference — but remember to unset the variable afterwards, otherwise subsequent loops will corrupt the array. The safer way is to use array_map: it returns a new array and has no reference traps.

Is making a database query inside a loop a problem?

Yes, it is a serious performance issue. Every iteration means a separate query; an array with a hundred elements produces a hundred queries. Fetching data in a single query and matching it in memory is the correct approach — this is called the N+1 query problem.

Summary

foreach is the default and safest way to iterate over arrays in PHP. Since it gives a copy of the element, modifying the array requires a reference, and it is mandatory to unset the variable after a reference-based foreach.

HexLibraryHexLibrary

Learn programming more clearly. Every command is explained line by line with colors, reinforced with runnable exercises, test your code instantly — all in one place, free.

Learn

  • Home
  • Languages & Lessons
  • HexCode

Company

  • About
  • Contact

Legal

  • Privacy Policy
  • Terms of Use

Other Projects

  • HexToolz
  • Free Service Manuals
© 2026 HexLibrary · The clearest way to learn code