HTML, XHTML and CSS All-In-One for Dummies - Andy Harris [218]
By Root 1332 0
foreach loop is a special version of the for loop that simplifies working with arrays. Here’s how it works.
1. Use the foreach keyword to begin the loop.
This tells PHP that you’re working with the foreach variation.
2. The first parameter is the array name.
The foreach loop is designed to work with an array, so the first parameter is the array you want to step through.
3. Create a variable to hold each element of the array.
On each pass through the loop, the $book variable will hold the current element of the $books array. Most of the time, you use a loop for an array because you want to deal with each element of the array. Using a foreach loop makes this easier.
4. Use the $book variable inside the loop.
The $book variable is ready to go. The nice thing about using foreach is you don’t have to worry about indices. The $book variable always contains the current element of the array.
You can see the results of both of these loops in Figure 4-3. To the user, there’s no difference. Both are simply text when it comes to output.
Figure 4-3: Two kinds of for loops are used to view these arrays.
Arrays and HTML
Arrays are great because they’re used to hold lists of data in your programming language. Of course, HTML already has other ways of working with lists. The
and tags are both used for visual representations of lists, and the