For and foreach loop in php

→ Are you a new visitor? Please visit the page guidance for new visitors ←

For and foreach loop in php

For and foreach loops are mostly used when working with arrays, but not only that of course. In my other examples, I created a simple snipped to show you the while loop in php, same example can be created with For loop.

Scenario

We have a small array and we need to print each element on a new line.

Solution using For loop

For loop needs a limit to be set, in our case, we set the limit to the total number of elements from within the array, using the count() php function to count all elements in the array.

Solution using Foreach loop

Foreach loop is more simple than the other one, you assign a variable to your elements directly and you use that variable in each iteration.

Output

Output in both cases will look like below:

Foreach looks much more simple right? Although performance wise when working with larger arrays, I believe For loop is better, also While loop is also an option to parsing arrays, it is similar to the For loop where you are comparing it to the count($list).

Request an article ←