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

Matteo Fossati
Matteo Fossati
3,938 Points

How can I check whether the second key is true in a foreach loop or not?

I'm stuck in this foreach loop. The first task is done (printing every flavor inside the foreach loop) while I can't make the if statement work: I almost surely wrote something wrong in terms of syntax. The second task is to print only flavors which are in stock. Could someone please help me?

Thanks so much

Matteo

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 $chiave => $gusto) {
  if( $chiave['in_stock']) {
print_r ($gusto);
  echo $gusto;
    }
}
?>

1 Answer

Loop over the $flavors array and store each one in a temporary $flavor variable. If that $flavor is in stock echo it to the screen:

<?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; 
  }
}
?>