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 Creating the Display Function

Variables used in foreach loop are confusing

This is more of an observation than a question.

For me, the variables used in the foreach loop are confusing and not explicit and took me too long to figure out. From my understanding a foreach loop works like this....

foreach($array as $key => $value) { 
     // some code here; 
}

The instructor uses $catalog to describe the array, which is good, but then uses $id to describe the $key and $item to describe the value. This is way too confusing!

When I think of an $id I think of identification, such as the an identification# or a SKU#. I kept thinking the instructor was referencing the SKU#, for example, the SKU# 101 from the book "Design Patterns".

id, year, genre, format, category etc. are not IDs. They are keys or categories.

Furthermore, the year 1994 is not an item, and the genre "Tech" from the design patterns book is also not an item. They are values belonging to their category.

In my opinion it is best to name the variables in the loop as such....

foreach($catalog as $key => $value) { 
     // some code here; 
}

Again, this is only my opinion and is not to say I am entirely correct.

It would be nice to hear thoughts and opinions from others. I've been having way too many problems with this part of the lesson.

Cheers!

1 Answer

After revisiting this, I finally have a better understanding. The variables make more sense to me now and I now understand why the instructor would use them, but they can still be confusing.