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.

PHP Build a Simple PHP Application Working With Functions Displaying Only Four Shirts

is 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?

just 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.

1 Answer

Yes, 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
Prakhar Patwa
11,260 Points

hey Manav, that thing was in my mind but i was placing in the wrong declaration. Thankyou.