When working with arrays in PHP, specifically in the context of WordPress (which is obviously the norm around here), it’s become pretty common to see code using the foreach
construct versus a vanilla for
loop when working through an array.
Personally, I think it’s easier to read and that it works especially well when working with an associative array. That is, it’s really useful when you need to iterate through a collection that’s indexed with a unique set of keys that aren’t necessarily in numerical order (which is something you’re more like to see in a for
loop).
Most who have been working in WordPress, let alone PHP, for sometime are likely familiar with everything that’s just been said. That is, when it comes to working with a collection, it’s easy to think
“Okay, so I’ve got a collection of information and I need to iterate through it. Working with a `foreach` loop is easy because it will allow me to traverse the list just like a `for` loop without having to initialize a variable, set an upper limit, and increment the iterator.”
Granted, maybe that’s a bit of a mouthful – maybe we just say “foreach
loops are easier” – regardless, there’s another way that we can think about using language constructs like this.
That is, rather than think of them as ways to simply iterate through collections of data, we can also think of them as ways that inform the decisions that we make when building a user interface.
Continue reading