foreach iterates arrays and Traversable objects by value or reference.
What It Does
foreach iterates arrays and Traversable objects by value or reference. The following examples distinguish a normal use case, a boundary case and a practical application.
Requirements and Compatibility
PHP 8.x and a local test environment. Apply input validation, correct error handling and the requirements of any optional libraries.
The code focuses on the core concept. Production implementation may also need routes, validation, persistence, authorization or deployment tooling.
Example 1: Basic Behavior
Start with the smallest meaningful working case.
<?php
foreach (['red', 'blue'] as $color) { echo $color . ' '; }
Example 2: Another Case
Examine the edge case and the observable result.
<?php
foreach (['alex' => 12, 'mira' => 15] as $name => $points) { echo $name . ':' . $points . ' '; }
Practical Example: Putting It to Use
Apply the technique to a small practical task.
<?php
$scores = [10, 12];
foreach ($scores as &$score) { $score += 5; }
unset($score);
print_r($scores);
Important Behavior and Edge Cases
Unset reference variables after a foreach-by-reference to avoid accidental later mutation.
Comparison with Related Functions or Approaches
| Option | What it means in practice |
|---|---|
| Foreach Loops | foreach iterates arrays and Traversable objects by value or reference. |
| Related approach | Use for when an index-driven counter is necessary. |
Common Beginner Mistakes
| Mistake | Correct approach |
|---|---|
| Ignoring the important boundary for Foreach Loops | Unset reference variables after a foreach-by-reference to avoid accidental later mutation. |
| Assuming a related mechanism has the same behavior | Use for when an index-driven counter is necessary. |
Key Takeaways
- foreach iterates arrays and Traversable objects by value or reference.
- Unset reference variables after a foreach-by-reference to avoid accidental later mutation.
- Use for when an index-driven counter is necessary.
Before adapting these examples, verify the return values, test the failure paths and confirm that your application meets its security and environment requirements.