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
Eldy Voon
3,812 PointsRight now, this block of code displays all five ice cream flavors that this store carries. Modify it to display only the flavors that are in stock.
<pre><?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);
foreach($flavors as $flavor) { if($flavors["in_stock"] == true){ echo $flavor["name"] . "\n"; }
}
?></pre>
didn't work :(
2 Answers
Spenser Hale
20,915 Points<?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);
foreach($flavors as $flavor) { if($flavor["in_stock"] == true){ echo $flavor["name"] . "\n"; }
}
?>
your if than statement was using plural "flavors" when should be "flavor" because we are taking all "flavors" and making it a working variable "flavor"
Arturo Espinoza
9,181 PointsI got my answer this way. Did I get luck or is this the correct way?
<?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 => $value) {
if ($value["in_stock"] == true){
echo $value["name"]. '<br/>';}
}
?>