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 thoughts on “First and Last collection item in Magento

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top