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 PHP Arrays and Control Structures PHP Loops Looping with PHP

Question about the foreach loop.

Hi. I just want to make sure that i fully understand what's going on :]

we have this multi-dimensional array:

$flavors = array();
$flavors[] = array("name" => "Cookie Dough",      "in_stock" => true);
$flavors[] = array("name" => "Vanilla",           "in_stock" => false);
$flavors[] = array("name" => "Avocado Chocolate", "in_stock" => false);
$flavors[] = array("name" => "Bacon Me Crazy",    "in_stock" => true);
$flavors[] = array("name" => "Strawberry",        "in_stock" => false);

in order to loop through the multi-dimensional array we use the foreach loop.

my question is about this code:

foreach($flavors as $flavor) {
    echo $flavor["name"];
  }
}

$flavor in the foreach loop represent the "values" of each key, for example in the $flavors array,in the first array iteration $flavor represent "Cookie Dough" but why we have to add the key of the value which is "name" >>> $flavor["name"] in order to access the value? WE do it because we have another key-value pair? and in that way we can differ between them?

thanks in advance!

2 Answers

Steven Parker
Steven Parker
229,644 Points

Each element of the "$flavors" array is another array, so the "$flavor" represents the entire smaller array which has multiple key/value pairs in it.

So the key is used with "$flavor" to select a specific value associated with that key. And yes, you were right about that part.