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 trialKelvin Atawura
Front End Web Development Techdegree Student 19,022 Pointsis there any other way to display the last 4 items
l am really confused about what Randy did in the video to display the last four items. is theres any other way of doing like using a foreach loop?
1 Answer
manav
5,466 PointsYes, of course!
Instead of using the following code:
<?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;
?>
You could also use the PHP's internal function array_reverse() to reverse the order of products array, so we can display the first four shirts without looping through the whole array:
<?php
$reversed_products = array_reverse($products);
$position = 0;
foreach ($reversed_products as $product_id => $product) {
$position = $position + 1;
if ($position < 5) {
echo get_list_view_html($product_id, $product);
} else {
break;
}
}
?>
Prakhar Patwa
11,260 Pointshey Manav, that thing was in my mind but i was placing in the wrong declaration. Thankyou.
shawn stokes
5,651 Pointsshawn stokes
5,651 Pointsjust watched the video. between 2min and 5min he explains how this works. as for your question yes there is another way to do it but it take more code and really is not an option for this unless you were wanting to fully automate the process. he is using a foreach loop he is cycling through it counting all the position in the array and then echoing out the shirt that meet his argument of being the last 4 in the array.