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

trio-group I.AM
trio-group I.AM
24,142 Points

Looping with PHP

I have done it with my Code Editor and everything is working properly but here is somehow not working.

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);


$status = 'available';

foreach ($flavors as $flavor){
    if($status === 'available' || $flavor['in_stock'] == $status)
      echo "<li>";
      echo $flavor['name'];
      echo "</li>";
}

?>

2 Answers

Jerry Gomez
Jerry Gomez
4,931 Points

I don't think you should use $status === 'available' as the previous poster mentioned. Since that will always be true.

I did it using a foreach loop, then checking the selected items 'in_stock' value as true or false. If true, then display the name of the flavor.

//add your code below this line
foreach($flavors as $oneFlavor)
{
  if($oneFlavor['in_stock'] == true)
    echo $oneFlavor["name"];
}

In the line if($status === 'available' || $flavor['in_stock'] == $status), $status === 'available' is always true since the value of $status is not changed. You could change || to && so that both conditions must be true, or change the line to if($flavor['in_stock'] == true) or if($flavor['in_stock']).

Instead of

      echo "<li>";
      echo $flavor['name'];
      echo "</li>";

try echo $flavor;. The challenge is not expecting the flavors to be list items.

To do multiple statements after an if statement, you could try surrounding the code block with { and }, such as

    if($flavor['in_stock']) {
      echo "<li>";
      echo $flavor;
      echo "</li>";
    }

but this does not pass the challenge. If you leave off the { and }, only the first line after the if statement is inside the if block, and the lines after the first line will run regardless of the truthiness of the if statement's condition.