Magento – Get item at nth index from a collection

collection;magento-1.9product-collection

Is there a way to get an item at the nth index from a collection without necessarily loop over all the collection?

Best Answer

I don't believe there is a way to grab a specific index from Varien_Data_Collection (however I would love to be proven wrong on this!)

Notwithstanding, here are my attempts.

    /**
     * Method 1,
     * Using LIMIT to grab the 9th item, a new query for each item.
     * Inefficient but fun!
     */
    $collection = new Varien_Data_Collection();
    $collection->setPageSize(1);
    $collection->setCurPage(9);
    $ninthItem = $collection->getFirstItem();

    /**
     * Method 2,
     * the collection toArray functionality.
     *
     * It actually iterates through the collection within the toArray call,
     * but at least it saves you from doing the iteration yourself!
     */
    $collection = new Varien_Data_Collection();
    $collectionData = $collection->toArray();
    $ninthItem = $collectionData['items'][8];