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 trialMatteo Fossati
3,938 PointsHow 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
<?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
scribbles
21,173 PointsLoop 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;
}
}
?>
Matteo Fossati
3,938 PointsMatteo Fossati
3,938 PointsThanks! That worked :D