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

nicholasgryczewski
nicholasgryczewski
2,919 Points

Modify the foreach loop to display only the flavors that are in stock

I got it to display the correct flavors and was excited but then it said that it wasn't correct and task 2 was no longer passed???

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 $flavor) if($flavor["in_stock"]==true) {echo $flavor["name"] . "<br />\n"; } ?>

try to do it with the brackets around the foreach and also remove the "==true" from the if statement

Dave Schenk
Dave Schenk
256 Points

If you format this you'll see that you're just missing brackets

foreach(){
  if(){

  }
}
Antonio De Rose
Antonio De Rose
20,884 Points

I ran your code, and it perfectly works fine for me, try running your code yourself.

I agree with both Haris and Dave, make it a habit of indenting the code, it will be best practice to have the code like as

<?php
foreach ($flavors as $flavor){
  if ($flavor["in_stock"]){
  echo $flavor["name"]."<br>";
  }
}
?>
``

1 Answer

Abdelmadjid Cherfaoui
Abdelmadjid Cherfaoui
3,230 Points

I went with the simplest solution

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