Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member
Foreach loops are a little different from the previous two types of loops. Foreach loops are going to take an array and loop through each item of the array until it gets to the end. If you think back, while loops and for loops know whether to quit or to keep looping by testing if a condition has been met. Foreach loops, on the other hand, are going to know whether to quit or whether there are items left in the array to loop over. The end of the array is what ends the looping. There's really just two approaches to looping. Let's use a real-world scenario for a second. Imagine that I have a classroom with 20 kids in it.
And I have to put name tags on all of them. Now, I could just go around the room. And I could put a name tag on each kid and keep track of the numbers as I went. And knowing that there are 20 kids, when I had gotten to the number 20, I'd know I was done. Or, since I know that I have a finite set, I could just line them all up, start at the beginning and move down the line. And when I got to the end of the line, I would know I was done. I wouldn't have to keep track of the count as I was going. I mean, I could count. I could certainly know that I was on the fourth kid, but I wouldn't have to.
I could just start at the first kid, go to the second kid, and then the third kid, until I got to the end of the line. That's how a foreach loop works. The syntax is also a little bit different. We have foreach, and that's foreach all run together. No spaces, no underscore or anything like that, just foreach. And then, in parentheses, we have a special statement. The first thing we're going to provide is the array that we're looping through. So, that's what I've got there with the variable array. It doesn't have to be called array. It's a place holder. To show you that that's where the array goes.
And then, we've got this special keyword, as. That's part of the foreach statement. It's a special keyword that it uses. And then, we have another variable after that, called value. Now, value also can be named something else. What it's doing though, is that each time it goes through the loop. Each item in the array is going to be assigned to this variable value. Value is just now being defined here. Array is a value that existed before the foreach statement, value doesn't. Value is something that we're creating right now for use only inside the loop. And then each time through the loop, we have access to that variable. And that variable is a reference to the item in the array that we're currently working with.
If that at all seems fuzzy, don't worry. It'll make a lot more sense when we see an actual concrete example. Now, just like the other loops though, I think it's a good practice to put curly braces around our loops. So, it's very clear where the loops start and stop with a single nine statement. It's not necessary, but with a multi-line statement, it is. Now, I want you to notice something else about this foreach statement. It's the same thing that I told you at the beginning. Notice that there is no condition here. There's no condition and there's no mechanism for incrementing, right? Those are two things that both of the while and for loops used. They had a condition that had to be met to know when it should exit the loop, and increment it.
This one doesn't. Why not? Well, because the condition for exiting is when it gets to the end of the array. And it doesn't need to increment because it knows when it gets to the bottom of the loop, it knows what it should do. It should go to the next item in the array. So, both of those are missing here. All we're doing is saying, for each one, assign it to this variable, and then do the loop. Let's try an example. An example will make this clear. Let's open up basic value HTML again. Let's do Save As, this time we're going to save it as foreachloops.php. I'll call it loops foreach, no spaces.
So, I'm just going to paste in our first example here. I've got an array filled with numbers, and I'm assigning it to the variable ages. So now here, I have my foreach loop. And it's going to take that array the ages points to as age. So, each one of these values is going to be assigned to the variable age temporarily. Notice the difference here, the singular and the plural, right? Age and ages. Ages was defined before age is just now. Being introduced here. Now, each time through the loop I have access to the age, right here, to use, right? Let's bring that up and try it in the browser.
Go to Firefox, and instead of for loops, I'm going to bring up foreach loops. See how that works? Age 4, 8, 15 and so on. Every time it goes through the loop, the next item is assigned to age so that I can work with it and it just moves down this list. If there are six items in the array, well then it's going to loop six times. This is very useful when you want to traverse an array. Imagine that you have a list of a user's last 15 orders that you want to output to them. Well, that's an array. The 15 orders are an array.
You could use a while loop or a for loop as you iterate through those, but the foreach loop really works better. Because the foreach loop says, alright, start at the beginning of these orders. And let's start going through them. And we get to the end, we're done. Loop through it however many of them there are. If there's 15, show all 15, if there's 20, let's show 20. And it's especially nice, because then each time through the array. The customer's order would get assigned to a variable called order. That would have everything we needed to then output the same way that we're working with age now. And you may be asking well, if this works for regular arrays, but what about associative arrays? Remember we talked about associative arrays before where they have a key and a value? We just have to modify our syntax slightly to make associative arrays work with foreach. The overall structure is the same, but we're going to have array as. And we're going to have two variables that we're going to assign. One for the key, and one for the value.
Now, they don't have to be called key and value. They can be called anything you want, but the important part is that we have two variables. And between them, we have the equals greater than sign. Just like we use in the associative array to separate our keys and values. Let's try an example using associative arrays. So again, I'm going to paste our block of code. Remember, you can pause the movie if you need to copy this down. What I've got here is a person. And that person has an array of data. And it's labeled, first name Kevin, last name Skoglund, address, city, state, zip, right? All that information. And then for each item in person as, I'm calling it the attribute and the data. Not key in value, these are the key and value.
That's the technical name for it, this is the key and this is the value. But I'm going to be assigning them to the variables attribute and data. Now on the next line here, I've got a couple of string functions that work. We talked about some of these before. We have UC words and string replace. What I'm doing is cleaning up this attribute which uses underscores in it and lower case to make it look nicer. Take away the underscores and upper case the first words. I'm calling that attribute nice and I'm outputting attribute nice and the data. Let's take a look. I'll save it come back over to Firefox, reload it, and there we go.
First name Kevin, last name Skoglund. Address 123 Main Street, and so on. See how that works. I've specifically wanted to show you this example by using the ucwords as string replaced. because this is the kind of thing you'll get back from your database as the name of a database field. And we would want to clean that up before we showed it to end user. We don't want to show them all the underscores and everything. I want to show them something that's a little bit nicer. So, I'm going to give you one more associative array example before we move on. Here, I've got just another array, and I've got brand-new computer.
One month of Lynda.com and learning PHP are the keys. The values are 2000, 25 and null. So, I've assigned that to prices. For each item in prices, I'm going to assign those to item, because each of these are items. And each of these are prices, and each of these is going to be assigned to price. because that's what they are, they're prices. And then, as I iterate through each of these, I'm also going to have a conditional statement here. That's going to check to see whether or not price is an integer, which will be true for the first two but not for the last one. And so, let's go ahead and just reload that up over here. It's a little bit of a joke.
You can see, brand new computer, $2,000, one month of Lynda.com, $25, learning PHP, priceless. Hopefully, you now understand how foreach loops work. Whenever you're working with an array, you should first think about using foreach loops before you go to one of the other types. Because foreach loops are tailor made for working with arrays. So, if you have an array chances are foreach loops are what you want.
Get unlimited access to all courses for just $25/month.Become a member