Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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
215,357 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.