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

Egor Banshchikov
Egor Banshchikov
4,736 Points

Using foreach

The task is to display the name of each flavor in the array. I'm getting the error message: Illegal offset type in index.php on line 12. So... what's wrong?

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 $item) {
  echo "$flavors[$item]['name']";
};
?>

2 Answers

Egor Banshchikov
Egor Banshchikov
4,736 Points

Okay I figured it out myself:

foreach ($flavors as $item) {
  echo $item['name'];
};

I don't need double quotes and I don't need using $flavors inside my foreach loop bc I already defined that I'll be looping through $flavors

Kevin Korte
Kevin Korte
28,149 Points

Yay! Good job. One think I just want to make you aware of, and it doesn't affect the output of the code, and in this small example, it doesn't matter, but as your skillset grows, it would be more common to see the code as

<?php
foreach ($flavors as $flavor) {
  echo $flavor['name'];
};

Just reading through that, it's pretty clear what's what. $item is a bit nondescript. But this way, we know $flavors is our array, $flavor is a single instance from the array, and $flavor['name'] is pretty descriptive as to what we can expect to get back.

Same patter would apply. Plural and singular. It could be $cars and $car, $houses and $house and so on.

Just something to keep in mind as you go along. Happy coding.

Try getting rid of the double quotes on the line that's inside the foreach loop.

That might not help, 'cuz I'm rather new to PHP :)

Good luck and have fun coding!

Hope this helps, Alex