n00bly n00bly - 4 months ago 27
PHP Question

PHP foreach loop skip first 3 items

I have a list of 6 products that i want to split in 2 lists of 3 products next to each other. The list are made within a foreach loop, the first list stops after the count == 2, so 3 items wil be displayed. The second list should start with the fourth item. How can i achieve this?

This is wat makes the first list of 3 items:


<?php
$_categoryId = explode(' ', $category['id']);
$count = 0;
$_productCollection = Mage::getModel('catalog/category')->load($_categoryId)
->getProductCollection()
->addAttributeToSelect('*')
->setOrder('date_added', 'DESC');
?>
<?php foreach ($_productCollection as $_product): ?>
<li class="category-row-list-item">
<a class="product-name" href="<?php echo $_product->getProductUrl() ?>">
<?php echo $this->htmlEscape($_product->getName()) ?>
</a>
</li>
<?php
if($count == 2) break; // Stop after 3 items
$count++;
?>
<?php endforeach ?>



Best regards,
Robert

kb. kb.
Answer

For simplicity you could repeat the foreach statement but doing the opposite and continue on the first three items.

<?php foreach ($_productCollection as $_product): ?>
<?php
    $count++; // Note that first iteration is $count = 1 not 0 here.
    if($count <= 3) continue; // Skip the iteration unless 4th or above.
?>
<li class="category-row-list-item">
    <a class="product-name" href="<?php echo $_product->getProductUrl() ?>">
        <?php echo $this->htmlEscape($_product->getName()) ?>
    </a>
</li>
<?php endforeach ?>

The keyword continue is used in loops to skip the current iteration without exiting the loop, in this case it makes PHP go directly back to the first line of the foreach-statement, thus increasing counter to 4 (since 4th, 5th and 6th is what we're after) before passing the if statement.

Commentary on the approach

I kept it coherent with your existing solution but a more clean way in this case would probably be to use the built in Collection Pagination.

If you use ->setPageSize(3) you can simply iterate the collection to get the first three products and then use ->setCurPage(2) to get the second page of three items.

I'm linking this blog post on the topic here just to give you an example of how it's used but since I don't know your comfort level in working with collections I retain my first answer based on your existing code.