PHP Build a Basic PHP Website 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.