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 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:

<?php
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:

<?php
$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.