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 trialAttila Balog
5,217 PointsI don't really understand the modified foreach loop. What does return this code: foreach($catalog as $id => $item) ???
I don't really understand the modified foreach loop. What does return this code: foreach($catalog as $id => $item) ??? Why did she put an arrow just like when you add new information about a particular item in an associative array. What is the function of that arrow?
3 Answers
Ben Schroeder
22,818 PointsYou use that syntax when you want to iterate through all items in an array, getting both the key and the value to use in the loop, instead of just the value.
See the PHP docs: http://php.net/manual/en/control-structures.foreach.php
Algirdas Lalys
9,389 PointsHi Attila, for example we have simple associative array.
$catalog = array(
"title" => "A Design Patterns: Elements of Reusable Object-Oriented Software",
"img" => "img/media/design_patterns.jpg",
"genre" => "Tech",
);
If we use foreach without "=>" we can access only array value. For example:
foreach($catalog as $value) {
echo " VALUE = " . $value . "\n";
}
But if we use "=>" we can additionally access, key of the array.
foreach($catalog as $key => $value) {
echo "KEY = " . $key . " VALUE = " . $value . "\n";
}
Attila Balog
5,217 PointsSo, than the $id variable isn't referring to the index position. Am i right? It refers to the "key" and the $item to the "value".