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')

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.

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

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 ?


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