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

James Barrett
James Barrett
13,253 Points

Unclear on what 'id' is doing in the functions

Hi,

Really unclear on a particular piece of code in the array_category() function:

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

What exactly is $id doing/referencing? And why is it stored in the empty array which was initially declared at the beginning of the function?

2 Answers

Benjamin Larson
Benjamin Larson
34,055 Points

Hi James,

Inside the foreach loop, $id is referencing the key of the catalog array, which is basically it's unique identification code (hence, $id).

The loop is going through the entire array to see if the array index for category is the same as the category that's being specified for that page. If it is, it adds that $id to a new array, called "output", which will result in a collection of unique id's (the catalog array keys), for only those items which match the specified category.

Geoff Bowen
Geoff Bowen
1,877 Points

So glad someone else has raised this. It's took me a while to understand the foreach loop above because of the fact she referred to the 'key' value as $id. Why would she do that? It seems ripe for confusion. Having resorted to Google for the answer I now understand the code above, in layman's terms, does this:

In the array called $catalog (where you have loads of pairs like "genre" => "Tech" etc.) I want to assign the first part (the key "genre") to a variable called $id ($key would be clearer!!) and the value ("Tech") in to the variable $item.

(tagging James Barrett and Alena Holligan)

Juan Ferr
Juan Ferr
13,220 Points

The $output is returning an array of ids of products, eg: [104,105,201].....then when that function gets called from catalogue.php it stores that array of ids in a variable called $categories, which is used for a foreach loop, and each id( called $id in the foreach loop) is passed to the function that render a particular element to html using that id.........is that a little more clear?....when you assign something to a $variable[]= means the new element is placed in the last position of the array at the moment......