Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP Build a Simple PHP Application Listing Inventory Items Introducing Arrays

adrien kovanic
adrien kovanic
5,727 Points

flavor / flavors

Hi I still can't figure out why a foreach there is flavors as flavor... because there is no "flavor" for the flavor has not yet been define.. thanks a lot

3 Answers

Gavin Ralston
Gavin Ralston
28,770 Points

If you haven't gotten around to checking out the video, here's my explanation:

foreach is doing this:

  • Going through each item in your array
  • Putting that item in the variable that you define in the loop statement to hold that single item
  • Running the code in the braces on that single item

So you defined your array, or it was defined for you, and that's the first part of the statement.

You need to define a variable to hold each item each time through the loop, though, so what you're doing with that "as $whatever" section is saying "Use $whatever to hold each item as you apply the following code to it"

That way you can access it in the code you want to execute (in the code block after it) on each item.

So it makes a lot of sense to name things in the plural as your array, then just naturally use the singular as the variable you define with as Like so:

<?php

foreach ($shirts as $single_shirt_from_the_shirts_array) {
    starch($single_shirt_from_the_shirts_array);
}

// or more appropriately....

foreach ($chickens as $chicken) {
    behead($chicken);
}

foreach ($actions as $action) {
    reaction($action);
}

// or you could get (relatively) clever-but-ambiguous (and much harder to read)

foreach ($benjamins as $bill {
    rain($bill);
}

Think of $flavor as a new variable that is assigned the value of the current element from the array $flavors. It's basically assigning a value of whatever flavor is from your list of flavors and holding in that that variable for that particular pass through the loop. Then the value is changed on the next pass through etc.