Loops · Lesson 3 of 6
for Loop
Use initialization, a condition, and an update for counted repetition.
Lesson
A for loop groups its initialization, continuation condition, and update expression in one place. It works well when the number of iterations or index progression is known. Use a descriptive counter and check array bounds carefully, especially when an index comes from user input.
The final index is exclusive in the condition below, so the loop visits indexes zero through three.
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 for 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
for Loop
PHP
for ($index = 0; $index < 4; $index++) {
echo $index, ' ';
}
Expected output
0 1 2 3
Key points
- Use initialization, a condition, and an update for counted repetition.
- 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.