We have almost covered all the flow control statements and loop structures as part of this blog series on PHP Programming. In this last blog on loops before we move on to functions parameters and formatting numbers, we will discuss about the ‘foreach’ statement. You must be wondering, ‘we have already learnt about the ‘for’ loops, so why ‘foreach’ now? Can we just not solve our problems with the loops that we have already learnt?” The answer to this is simple and one that I have already mentioned in a previous blog. Optimization is the need of the hour and you need to be fast to make sure that you do not lag behind. For optimization in your WebPages, you must use the right loops in your PHP script, and to use the right loop in your PHP script, you must have the knowledge of which loop is right at which point.

What is ‘foreach’ statement and how is it different from the ‘for’ loops?

I am sure you must be more excited and eager about the second part of this question, but we will still start with the first part as we believe, having a strong base is more important than building a high tower. As the name suggests, ‘foreach’ is used to iterate through each and every value in an array. Now, the important thing to note in that definition is the use of the word array as ‘foreach’ only works on arrays and not on any other element. Now, I am going to counter my own statement, in fact just the previous statement, as this statement that ‘foreach’ only works on array is not entirely true, but we will keep it to that for the time being, until you are comfortable with PHP and array pointers and how the values are fetched in the ‘foreach’ statement.

In the above example, the values inside the array named ‘$names’ are iterated one at a time and are printed in the same sequence. You might notice the difference in the syntax of a ‘for’ loop to that of a ‘foreach’ loop. It is important to note that even the most experienced programmers sometimes do mistakes with the syntax of the ‘for’ loop and the ‘foreach’ loop. I hope the readers of this blog will not fall in the same category.

Note:

The internal array pointer is automatically reset to the first element of the array when the ‘foreach’ loop starts for the first time.

Given the first statement, you do not have to call reset() in a ‘foreach’ statement.

Changing the internal array pointer within the loop may lead into unexpected results from the loop. Therefore, such a practice must be avoided.