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.
Alex Forseth8,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?
Stuart Wright41,102 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.
Steven Jackson11,465 Points
Thanks for the answer Steve! I'm adding a bit more because I was very confused by this at first. The $id parameter is not used in the function for some reason!
If you inspect the output string below the function you wont see the $id parameter being used like $item parameter. The $item parameter is used to pull key value pairs and shows up in the $output string. This is especially confusing because $id is used as a working variable in both foreach loops.
Test by removing the $id parameter from all three instances of our function (get_item_html($item/$catalog[$id])). After this, leave it as a working variable in both loops(foreach($catalog as $id => $item) and nothing breaks. I hope this helps!