How to Loop Through an Array in PHP (foreach, for)
Looping through an array is one of the most common tasks in PHP development. Whether you’re building a simple script or a large‑scale application, knowing the right loop construct can improve readability, maintainability, and performance. In this article we’ll explore the two primary ways to iterate over arrays in PHP: foreach and for. You’ll get clear syntax explanations, real‑world examples, and best‑practice tips.
Table of Contents
Why Loop Through an Array?
Arrays store collections of values—numbers, strings, objects, or even other arrays. Looping lets you:
- Process each element without writing repetitive code.
- Transform data (e.g., map, filter, reduce).
- Generate dynamic HTML or JSON output.
- Interact with databases, APIs, or files based on array content.
Using foreach
The foreach construct is the most readable and PHP‑idiomatic way to iterate over arrays. It automatically handles the internal pointer and works with both indexed and associative arrays.
Basic Syntax
foreach ($array as $value) {
// $value contains the current element
}
Accessing Keys and Values
foreach ($array as $key => $value) {
// $key is the index or associative key
// $value is the element's value
}
Example: Looping Through an Indexed Array
$fruits = ['Apple', 'Banana', 'Cherry'];
foreach ($fruits as $fruit) {
echo "I love $fruit<br>";
}
Example: Looping Through an Associative Array
$user = [
'name' => 'Jane Doe',
'email' => 'jane@example.com',
'role' => 'admin'
];
foreach ($user as $field => $value) {
echo "<strong>$field:</strong> $value<br>";
}
Modifying Array Elements Inside foreach
To change the original array values, iterate by reference:
foreach ($numbers as &$num) {
$num *= 2; // doubles each element in the original array
}
Using for
The for loop gives you explicit control over the index, making it ideal when you need to:
- Access elements by numeric position.
- Iterate a specific number of times (e.g., skip elements).
- Combine looping with other arithmetic operations.
Basic Syntax
for ($i = 0; $i < count($array); $i++) {
// $array[$i] is the current element
}
Example: Looping Through an Indexed Array
$colors = ['Red', 'Green', 'Blue'];
for ($i = 0; $i < count($colors); $i++) {
echo "Color #{$i}: {$colors[$i]}<br>";
}
When to Prefer for Over foreach
- You need the numeric index for calculations (e.g., pagination offsets).
- You want to loop only a subset of the array (e.g., first 5 items).
- You’re working with a
SplFixedArrayor a custom object that implementsArrayAccessbut notTraversable.
Performance Considerations
Both loops are fast, but there are subtle differences:
- foreach internally uses a copy of the array pointer, which can be slightly slower for very large arrays if you also call
count()inside the loop. - for with
count($array)in the condition recalculates the length on each iteration. Cache the count beforehand for optimal speed:
$len = count($items);
for ($i = 0; $i < $len; $i++) {
// processing...
}
In most real‑world applications, the performance difference is negligible. Choose the construct that makes your code clearer.
Best Practices
- Prefer
foreachfor readability. It conveys intent without manual index handling. - Cache
count()when usingfor. This prevents unnecessary function calls. - Use references only when you really need to modify the original array. Unnecessary references can lead to hard‑to‑track bugs.
- Validate array data. Always ensure the variable you’re looping over is actually an array (or implements
Traversable) before the loop. - Escape output. When printing array values into HTML, use
htmlspecialchars()to avoid XSS.
FAQ
Can I break out of a foreach loop?
Yes, use break; to exit the loop early, or continue; to skip to the next iteration.
Is there a difference between foreach and while (list())?
The while (list()) construct is older and less readable. foreach is recommended for modern PHP code.
What if the array is empty?
Both loops will simply not execute their bodies. You can check with empty($array) if you need to display a fallback message.
How do I loop through a multidimensional array?
Nested loops are the usual approach. Example:
$matrix = [
[1, 2],
[3, 4],
[5, 6]
];
foreach ($matrix as $row) {
foreach ($row as $cell) {
echo $cell . ' ';
}
echo "<br>";
}
Can I use foreach with objects?
Yes, if the object implements the Traversable interface (e.g., Iterator, Generator).
Conclusion
Looping through arrays is a fundamental skill for any PHP developer. foreach offers clean, expressive syntax for most use‑cases, while for provides fine‑grained control when you need it. By following the best practices outlined above, you’ll write code that is both efficient and easy to maintain.