Limit results collection in Magento

Many times need arises to limit collection for say pagination or for any customization.

I am listing here an example which shows how to limit the collection.

I have used the Product Model below.

<?php
$limit = 5;
$starting_from = 2;
$product_collection = Mage::getModel('catalog/product')->getCollection()->setOrder('name', 'asc'); //getting the product collection, results are ordered by product name
$product_collection->getSelect()->limit($limit,$starting_from);	//where	$limit will be the number of results we want, $starting_from will be the index of the result set to be considered as starting point (note 0 is the index of first row)
//this will ouptput 5 records starting from 3rd record
foreach($product_collection as $_product)
{
	echo $_product->getName().'<br/>'; 
}
?>

Suppose the first 10 products (ordered by name) are

A
B
C
D
E
F
G
H
I
J

The above foreach will output

C
D
E
F
G

10 thoughts on “Limit results collection in Magento

Leave a Reply to Pragnesh Cancel reply

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

Scroll to top