What are the differences between the for
loop and the foreach
loop in PHP?
It should be pretty simple
foreach
abstracts away some of the complexity and is usually easier. I use this whenever I don't need to know the numerical index of the array or $key => $value
won't provide me with it.
for
is the older C style where you must first perform a count()
so you know how many iterations the loop requires. It is useful when you need to know the index, or to count backwards or step through in different groups.
A "for" loop gives you an incrementing number (in its most common use) which you can use any way you like.
"foreach" is a special construct made for looking at successive members of an array.
As an example, you can use a "for" loop to create something that does what "foreach" does. But foreach does that with less required code.