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

"Your are not using the variable you defined in the foreach loop."

So, the code attached has been the only way I've been able to print the flavors to the screen successfully. However, I am told this is not the way to do it as I am "not using the variable I defined in the foreach loop."

When I change 'name' to $value, I am told I cannot use the $flavors array in my output, and I get an illegal offset type warning in the preview.

If I remove $flavors, then I get no output showing at all. Same thing if i put something like echo $id[$value].

What am I doing wrong? Would appreciate anyone's help so I can wrap my brain around this!


$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);

//add your code below this line
foreach ($flavors as $id => $value) {
  echo $flavors[$id]['name'];

2 Answers

You're iterating the $flavors array. $id is the key and $value is the value. In this case, $value is also an array. To access the array by key, you may do $value['name'] or $value['in_stock'] depending on what you're looking for.

Thank you! These arrays were getting a little intense for me, but your answer definitely made some stuff click! I appreciate it!