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 trial
Eric Flowers
9,472 Pointsforeach loop syntax question
In the "Including the Products Array" video Randy changes the foreach loop to include the syntax
<?php foreach($products as $product_id => $product) {
is the "=>" operator what assigns the keys to $product_id?
3 Answers
Shawn Gregory
Courses Plus Student 40,672 PointsEric,
The easiest way to think of this is the following:
foreach($products as $product) $products is the array and $product is the value of each in the array
foreach($products as $id => $product) $products is the array, $id is the array key, and $product is the value
$products = array(1111 => 'Pie', 2222 => 'Cheese', 3333 => 'Milk', 4444 => 'Butter');
foreach($products as $product) {
echo $product.',';
}
This will output: Pie, Cheese, Milk, Butter
foreach($products as $id => $product) {
echo $id.' is '.$product.',';
}
This will output: 1111 is Pie, 2222 is Cheese, 3333 is Milk, 4444 is Butter.
Hope this helps.
Cheers!
banned banned
Courses Plus Student 11,243 Points$product_id holds the $product item, this is called an associative array.
$array = ['key1' => 'item1', 'key2' => 'item2'];
you could say echo $array['key1'];
$product_id => $product
in this case $product_id is the key so he also wants the key from the array and use it in the foreach loop.
Eric Flowers
9,472 PointsThanks guys!