Good day, fellow reader.
Two weeks ago I was talking to a colleague, who has plenty of years of PHP expertise, and he was amazed by his personal discovery of the "for each" loop. I couldn't hide my surprise at how could that knowledge be elusive to him, but after my initial reaction, that could be portrayed like this:
I said: "well, it's useful depending on the case". He stated that many times he needed to apply the same behaviour to every page in a set of pages. And how that structure seemed more natural for him, so he was using it as much as he could.
That got me thinking into the real concept behind the for each loop, how can it be used, abused. I also wonder, how he could go by so many years without using it and by no means being powerless in his ability to make quality code.
So, what is actually a for each? It's nothing more than a for loop, that takes into consideration every item in a set of items, and applies (hopefully) some action to it.
For each features
Disclaimer: "for each" loop may vary from language to language.
Traversing items in a collection
Yeah, yeah, you got it. I just like the word traversing and wanted to include it in some text.
It is a loop sentence
That implies two important things.
- Behind the scenes, usually it's written with a for loop with some perks.
- There's nothing you can do with a foreach you could not achieve with a classic for.
Doesn't keep a reference to the current index
This doesn't mean you can't get the index of the current item inside a for each. It's just that it (usually) was not designed for it. Attempting that would mean extra work. From getting an index from a callback, up to finding the current element in the collection you are already iterating. It would be smarter just to use another kind of loop.
For each usually describes
"Apply this action to every item"
Instead of another kind of loops that are meant for
"Do this x times"
or
"Do this for items numbered a,b,x..."
Performance for != foreach
It's not that easy for a generic article on this topic to make such a statement without proper benchmarks. Let me just say that if your dataset is too big, or the performance in your app is critical, you should consider this. Write in the comments if you disagree or can prove me wrong.
Code
Pseudo-code
for each item in collection
// do this to item
Javascript
ES6 introduced the for...of
for (let book of books) {
book.ISBN = getISBN();
}
Or the functional way
books.forEach(book => {
book.ISBN = getISBN();
}
PHP
foreach ($posts as $post) {
echo $post->title;
echo $post->body;
}
Python
for beer in beers:
print(beer.name)
print(beer.IBU)
print(beer.ABV)
The interesting thing about foreach in python, is that it actually is the standard for loop. If you want the classic for (int i=0; i<array.length; i++)
for i in range(0, len(array)):
# Do whatever with i as index
See you around!
So tell me, do you find for each loop useful? In which language do you use it?