PHP For Each loops are specifically used to loop through arrays. For every value in an array, the Foreach loop will execute your PHP statement. Foreach loops are often used to display a list of information. For example, you may want to display a list of your customers automatically in a HTML table, or display a list of each item in a shopping cart.
Here is the Foreach syntax:
foreach ($array as $value) { php code & statements }
In the above syntax, each $array element is turned into a $value for that loop iteration. Once the loop repeats, it moves onto the next element in the array.
Here’s an example. We’ll create an array of automobile parts and we’ll display them to the browser.
<?php $carParts = array("tires", "engine", "seats", "muffler", "transmission"); foreach ($carParts as $carPart) { echo $carPart . "<br />"; } ?>
In human language we’re saying, “Hey PHP, every time you go through our array of car parts, I want you to assign the car part to the $carPart variable and then echo that variable to the browser. Can you do that for me? Thanks.”
So the output would be:
tires engine seats muffler transmission
Go back to Building PHP Scripts.