6

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

7

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];
  • A side note - steer clear of getFirstItem() unless you know the collection is small (or you have limited it to be small) as it loads the entire collection and then pulls the first item from the _items array which is pretty inefficient. – Jonathan Hussey Dec 10 '14 at 9:27
  • Doesn't pretty much any call to a collection that returns data call load(), which then loads the entire collection into the _items array? If so then it isn't really a problem with getFirstItem() and I'd see no better way of getting the first item from a collection. – Luke Rodgers Dec 10 '14 at 9:40
  • Yes anything which accesses the collection loads it (i.e. foreach etc) but in the case of getFirstItem() you are loading the entire collection but only pulling the first result. Why pull 1000 rows from the database when you actually only need 1? In your example it's fine because you have limited the collection but for those who refer to this answer later it's an important point. – Jonathan Hussey Dec 10 '14 at 9:46
  • calling toArray method on my Mage_Catalog_Model_Resource_Product_Collection all the items are turned into associative array. I need to have Mage_Catalog_Model_Product item instead of the associative array. Is there a way to do it? – gianis6 Dec 10 '14 at 9:48
  • @JonathanHussey, Aye I get you now. Sorry gianis6, not that I know of! – Luke Rodgers Dec 10 '14 at 9:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.