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

Foreach as $id => $item

Hello everyone, I don't completely understand how this function works.

"function array_category($catalog,$category) { $output = [];

  1. foreach($catalog as $id => $item){
  2. if(strtolower($category) == strtolower($item["category"])) {
  3.     $output[] = $id;
    }
    

    } return $output; }"

    1. foreach loops through all $catalog array items, as $id being the key and $item being the value of the key $id, right?
    2. We input the category parameter by ourselves, for example "books". Then it checks if the $item["books"] (key's key book?)? I dont understand this, is $id value or key and $item value or key?

The array element is like this:

$catalog[101] = [ "title" => "A Design Patterns: Elements of Reusable Object-Oriented Software", "img" => "img/media/design_patterns.jpg", "genre" => "Tech", "format" => "Paperback", "year" => 1994, "category" => "Books", <------- which one is $id and which one is $item? "authors" => [ "Erich Gamma", "Richard Helm", "Ralph Johnson", "John Vlissides" ], "publisher" => "Prentice Hall", "isbn" => '978-0201633610' ];

  1. We add the key only to the array?

Thank you

Denny Schouten
Denny Schouten
8,246 Points

hi, it's because in the function array_category you get the array keys of for example books back because it matches the section vs catagory of the data.php. So it only returns an array of keys of the matched section in the example case it would be the keys of the catagory books. With those keys you will display all the available books with the function get_item_html which requires only the keys of the array. Hopefully i cleared some up.