For and foreach loop in php
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.
1 |
$list = array("Andy", "Andrew", "Anthony"); |
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.
1 2 3 4 5 6 |
<?php $list = array("Andy", "Andrew", "Anthony"); for ($i=0; $i < count($list); $i++){ print ($list[$i]."<br/>"); } ?> |
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.
1 2 3 4 5 6 |
<?php $list = array("Andy", "Andrew", "Anthony"); foreach ($list as $element) { print ($element."<br/>"); } ?> |
Output
Output in both cases will look like below:
1 2 3 |
Andy Andrew Anthony |
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).