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

Alex Forseth
Alex Forseth
8,016 Points

get_item_html function structure. How does it work?

How do the arguments (0:27 she says parameters but I am pretty sure they are arguments) $id and $item communicate with the associative array in the data.php file? How does the function know to assign $id to the catalog key and the $item to the interior array keys? When nothing inside of those arrays have been assigned a variable named $id or $item?

2 Answers

Stuart Wright
Stuart Wright
41,062 Points

At around the 3:00 mark, she initiates the foreach loop:

<?php
foreach ($catalog as $id => $item)

This is PHP syntax for looping over an associative array ($catalog), and assigning the $id variable to the current key, and the $item variable to the current value. These can then be passed into the function.

Alex Forseth
Alex Forseth
8,016 Points

so $id in the foreach loop passes itself to the $id in the function get_item_html below it?

mahdi askari
mahdi askari
15,174 Points

cant I remove " $id => " if not then why?

Steven Snary
Steven Snary
17,540 Points

For those that have noted that the $id s not used in the get_item_html() function - you are correct. In fact if you take the $id out from the parameter list in the function header and do not pass $id into the function call the code will still execute correctly.

$id is still required in the foreach expression since $catalog is an associative array and we want the foreach loop to separate the key and value from the $catalog array.

Maybe the key will be used in an upcoming lesson???