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

foreach($random as $id)

I'm getting crossed-up and having a hard time understanding what this line of code is doing?

$random = array_rand($catalog, 4);

foreach($random as $id) {
    echo get_item_html($id, $catalog[$id]);             
}

array_rand($catalog, 4) returns an array of 4 random keys from the catalog array. So let's suppose it returns [101, 104, 201, 202]. The returned array is assigned to $random so we have : $random = [101, 104, 201, 202];

//the loop Now the foreach goes over each number in the $random array and runs the get_item_html each time. As there are 4 random numbers, it will return 4 items on the page.

PS: the $id(i.e: 101) is used to get the current item; So i.e $catalog[$id] could be $catalog[101] which is the book "Design patterns".

Hope that helps