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

Evan Cook
Evan Cook
3,479 Points

Accessing an array inside an array with a foreach loop

When I input my code I'm creating the correct output for the question, but I'm being told I'm not using the variable in my foreach loop. Where am I going wrong?

index.php
<?php

$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 $key => $item) {
  foreach($item as $key => $name){
    if($key == 'name'){

      echo $name . "\n";
    }

  }
}

?>
Jonas Westerholm
Jonas Westerholm
10,754 Points

Although your code works it's overly complicated which probably throws the code checker off here. There's no need to use two foreach loops or check the key.

foreach($flavors as $item) {
    echo $item['name'];
}

1 Answer

<?php

$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 $flavor){
  if($flavor['in_stock']){
  echo $flavor['name'];
  }
}
?>