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 trialjason chan
31,009 PointsSo how does for loop work?
<?php
$total_products = count($products);
$position = 0;
$list_view_html = "";
foreach($products as $product_id => $product) {
$position = $position + 1;
if ($total_products - $position < 4) {
$list_view_html = get_list_view_html($product_id,$product) . $list_view_html;
}
}
echo $list_view_html;
?>
So can somebody tell me how this works in layman terms? LOLs
1 Answer
Ben Lockett
22,419 PointsHey Jason,
Ill try my best!
foreach($products as $product_id => $product)
This is looping through the array $products. In that array lets say you have some t-shirts and each t-shirts had an ID. This will place the key of the current item in "$product_id" which would be the ID of the T-shirt and it will then put the T-shirt in the "$product" variable.
This type of loop is good if you are working with an associated array when you want to reference the key etc.
To make things simpler you can simply write foreach($products as $product) but this would not give you access to the index or key.
The loop will then go through the the array and run the code you put inside the {} for each item in the array.
Hope this helps
Ben
Jason Anello
Courses Plus Student 94,610 PointsJason Anello
Courses Plus Student 94,610 PointsHi Jason,
Did you need an explanation on what is happening inside the loop with the $position variable or an explanation of how
foreach
works (which Ben Lockett has already answered)?