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 Build a Basic PHP Website (2018) Listing and Sorting Inventory Items Displaying Categories

Sirin Srikier
Sirin Srikier
7,671 Points

I am getting this error Warning: Invalid argument supplied for foreach() in /home/treehouse/workspace/catalog.php

I checked and rechecked the code and I don't know where I went wrong.

<div class="section catalog page"> <div class="wrapper"> <h1><?php echo $pageTitle; ?></h1> <ul class="items"> <?php $categories = array_category($catalog,$section);

    foreach($categories as $id) {
      echo get_item_html($id,$catalog[$id]);

} ?> </ul> </div>

2 Answers

Lindsey Somerset
Lindsey Somerset
10,592 Points

I got the same error statement! Check the array_category function. On catalog.php, I did a var_dump() to the page like this:

<?php
$categories = array_category($catalog, $section);
var_dump($categories);

When on the Full Catalog section, it printed that it was an empty array. When I clicked on the books, movies, and music links; the var_dump() printed that it was an integer! I went to the array_category function and realized I was missing the square brackets from this line:

<?php
$output[] = $id;

Without the square brackets, a catalog id number was being assigned to $output. That would return an error in the foreach loop because it doesn't accept a number type as an arguments. Apparently I missed the part when she added those square brackets. Hope this helps!

Nick Dim
Nick Dim
12,885 Points

That's exactly what my mistake was. I did a var_dump and realized that $output wasn't adding the $id's just assigned the last one

John Driscoll
John Driscoll
20,460 Points

Thank you, this answer helped me out. I made the exact same mistake.

I don't believe that array_category is a built in PHP function - unless it's included in a function you have already built? Try using just a normal array in your 'foreach' and that error message shouldn't come up anymore.

Lindsey Somerset
Lindsey Somerset
10,592 Points

In the tutorial, we created the array_category function and included it from another file.