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

Why part of loop was made a function?

In the video, the code within {} was made code, i am confused on why didn't the whole code was made a function e.g foreach ($catalog as $item), was left out. Why? and what is the difference?

1 Answer

Lindsey Somerset
Lindsey Somerset
10,592 Points

The page making the request has to send the info of what items it wants printed.

The catalog page sends every catalog id (outer array, ex: $catalog[101]) and that id item's respective values (inner array's key/value pairs) to the function:

foreach ($catalog as $id => $item) {          
     echo get_item_html($id, $item);

In the "Random Fun with Arrays" video later this stage, the index page randomly chooses catalog IDs and sends those random IDs to the function:

$random = array_rand($catalog, 4);
foreach ($random as $id) {
    echo get_item_html($id, $catalog[$id]);

Using this set up allows other pages to send different print requests to the function. Please let me know if this is not clear.