search
top

First and Last collection item in Magento

We the Magento developers work mostly with data collections. For accessing the data we use ‘foreach’ to iterate over collection.

$product_collection = Mage::getModel('catalog/product')
        ->getCollection()
        ->addAttributeToSelect('*');

foreach ($product_collection as $k => $v)
{
	echo $v->getName();
	echo '<br/>';        
}

What if we need only the first or last item from the collection, Magento gives an alternate way to do this.


 
 var_dump($product_collection->getFirstItem()->getData());
 echo $product_collection->getFirstItem()->getName();
 
 echo $product_collection->getLastItem()->getName();
 var_dump($product_collection->getLastItem()->getData()); 

If you your Collection data as XML, There’s a method for that also

var_dump($product_collection->getFirstItem()->toXml() );

If only a particular field is needed ?


var_dump($product_collection->getColumnValues('name'));

Also filtering can be applied.

var_dump($product_collection->getItemsByColumnValue('name','Couch')); //product with name Couch

2 Responses to “First and Last collection item in Magento”

  1. Anne Maria says:

    Thanks to this blog

  2. […] We the Magento developers work mostly with data collections. For accessing the data we use ‘foreach’ to iterate over collection. ? […]

Leave a Reply

top