PHP Build a Basic PHP Website Listing and Sorting Inventory Items Creating the Display Function

17,744 Points

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