In this HowTo i’ll explain what the PHP foreach loop is and how you might use it.
The PHP foreach loop is a built in PHP statement that allows you to loop through all the items in an array. Each item in the array is stored in a variable that you define and updates with each loop. Example:
"; } ?>
In the above example, there is an array (imaginatively called $array!) that holds various strings. Using the foreach loop you can loop through each item in the array and do something with it such as print it out. I called the item $item (can you tell my brain doesn’t have it’s creative switch on today?) but you could change it to anything you like. This is in contrast to the C-style for loop which you might have seen in PHP and other languages.
"; } ?>
You can also loop through associative arrays and access both the key and values stored.
"; } ?>
It’s worth noting that if you make any changes to the items in an array whilst inside a foreach loop, this won’t automatically modify the array. For example:
The first foreach loop takes each number in the array and increments it by one. But this $number variable is only available (it’s scope is) inside the loop. So when the loop exits, the value is thrown away. So when the second foreach loop prints out the numbers, the original values from the array are displayed.
Basically any time you have an array (or an associative array, like in the second example above) and you don’t need to keep track of the index of each element. With a traditional for loop, you will have a variable which is counting up or down which you can then use to reference elements in the array. This might be useful if you actually want to print out that index or use it in another function or method. If you don’t need the index, use the foreach statement instead.
The traditional C-style loop is what most new developers learn when trying to loop through an array. The foreach loop is much more compact and safe however. That is, there is always a chance you accidentally create an infinite loop with a C-style loop but this isn’t possible with foreach. Therefore, any time you don’t need to access the index of a loop, you’re probably better of using foreach.