Loops · Lesson 4 of 6
foreach Loop
Visit each value in an iterable collection.
Lesson
foreach iterates through arrays and other iterables without manual index management. Add a key variable when both keys and values matter. If you need to modify original array elements, iterate by reference carefully and unset the reference afterward to prevent later accidental writes.
For read-only display, a normal value iteration is clearer and safer.
Further guidance
Before running a loop, identify the value that changes and the condition that eventually stops it. Check empty collections and one-item collections as well as the normal case. Prefer foreach when iterating a collection, and keep early exits easy to understand.
Practice task: Create a fresh example for foreach Loop. Predict the result before running it, then change one input and explain why the result changes. Test a normal case and one boundary or invalid case where it applies. Compare your output with the example and note one rule you would use in a real project.
Code examples
foreach Loop
PHP
$languages = ['PHP', 'SQL'];
foreach ($languages as $language) {
echo $language, ' ';
}
Expected output
PHP SQL
Key points
- Visit each value in an iterable collection.
- Identify the loop state and a clear termination condition.
- Test empty and one-item inputs as well as the normal case.
Your learning progress
Finish this lesson
Optional practice
PHP playground
This site does not execute learner-provided PHP code. Connect a secured PHP sandbox service before enabling code execution.
Execution is disabled. No code is sent to a server.