The PHP for each loop is a special type of loop that is particularly suited to processing arrays. It allows us a way of performing the same set of commands on all the elements in an array without needing to know beforehand what the size of the array is. It is similar in operation to the PHP for loop.
As a result, the PHP for each loop offers a more robust method of processing all the items in an array. It relieves the burden of having to get the array size if we were using a for loop to process the array.
Have a look at our PHP for each loop tutorial below.
The syntax for the For Each Loop in PHP is shown below:
foreach (array as $value) { // code to execute } OR foreach (array as $key => $value) { // code to execute }
As we can see above, there are two methods of using the foreach loop. The one you use will depend on the type of array that you are processing. There are two examples below which show how each works.
You can refresh yourself on the types of arrays in PHP with our PHP Arrays Tutorial.
Take a look below at a simple example:
<?php $test[0] = 'Jack'; $test[1] = 'Jill'; $test[2] = 'Mary'; foreach ($test as $name) { echo $name . '<br />'; } ?>
The output would be:
Take a look below at a more complicated example:
<?php $opposites['clean'] = 'dirty'; $opposites['left'] = 'right'; $opposites['up'] = 'down'; foreach ($opposites as $word1 => $word2) { echo 'The opposite of ' . $word1 . ' is ' . $word2 . '<br />'; } ?>
The output would be:
A very powerful construct indeed. It allows easy manipulation of an entire array without needing to use regular for or while loops which can be a pain to set up. With the PHP for each loop we do not need to know or care about the actual size of the array that we are working with. It is designed to go through all the elements in the array regardless of the size of the array.
Thanks for stopping by Tutorial Arena for your PHP for each loop introduction. Feel free to move on to another PHP tutorial in our series.