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

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