How to use a for loop on a collection pulled from Magento

How to use a for loop on a collection pulled from Magento

July 9, 2026 · Illustrated author avatarBy Stefan Bogdanescu
How to use a for loop on a collection pulled from Magento

Debugging Magento Product Collection Loop Issues

If you’re working with Magento and trying to loop through product collections, you might encounter unexpected crashes or errors when using standard for loops. Let’s dive into why this happens and how to properly handle your product data.

The Problem: For Loops and Mage Collections

When you pull a collection from Magento using Mage::getModel('catalog/product')->getCollection(), the returned object is not an array, but a complex Mage_Core_Model_Resource_Db_Collection object. Standard PHP arrays allow direct indexing with integers, but Magento collections do not.

In your code snippet, when you attempt to access $collection[$j], Magento tries to treat it as an array index, which fails because the collection is not an indexed structure. This leads to a fatal error or white screen of death (WSOD).

$productFromStore = $collection[$j]; // Fatal error: Undefined offset for Mage_Core_Model_Resource_Db_Collection object

The Solution: Using Foreach Loops

The foreach loop is designed to iterate over objects and collections, making it the perfect fit for Magento data structures. When you use foreach, Magento automatically handles the iteration logic behind the scenes.

Here’s how to properly loop through your product collection:

foreach($collection as $product)
{
    // This code works fine
    $sku = $product->getSku();
}

In this case, $product is an instance of Mage_Catalog_Model_Product, allowing you to safely call methods like getSku().

Best Practices for Magento Loops

  1. Use foreach: Stick with foreach loops for any collection data from Magento. It’s the only safe way to iterate over these objects.

  2. Avoid direct indexing: Never attempt to index a Magento collection using array syntax, as it leads to fatal errors.

  3. Check your product count: If you need the total number of products, use $collection->getSize() instead of count($collection). The latter will not work correctly with collections.

Conclusion

When working with Magento collections, always rely on foreach loops for iteration. Direct indexing and standard PHP array methods are not supported by these complex objects. Remember to use getSize() for getting the count of items in a collection.

If you’re looking to make your Magento development more efficient, be sure to check out our Magento Development Services at Laravel Company. We specialize in helping businesses optimize their e-commerce platforms through expert coding and performance optimization techniques.

Happy coding!

Catalog Indexing Errors

Our network