Magento – How to get first item from product collection

categoryproduct-collectionproducts

On the category view.phtml if I get the category and then get a product collection, how can I get the first product form the collection assigned to $_product for use in the code? Here is what I have:

$_category   = $this->getCurrentCategory();
$_collection = $_category->getProductCollection();
$_product    = 
$_resource   = $_product->getResource();

I tried using foreach but kept getting errors.

Best Answer

To get the first item in a collection simply use the getFirstItem() function on the collection.

Example:

// this gets all the products
$productCollection = Mage::getResourceModel('catalog/products_collection');
// this line gets just the first product
$firstItem = $productCollection->getFirstItem(); 

Example 2 (for this particular question):

$_category  = $this->getCurrentCategory();
$_collection = $_category->getProductCollection();
$_product =  $_collection->getFirstItem(); // this will get first item in collection

Some other areas this can be used:

Customers

$customerCollection = Mage::getResourceModel('customer/customer_collection');
$firstCustomer = $customerCollection->getFirstItem();

Orders

$orderCollection = Mage::getResourceModel('sales/order_collection');
$firstOrder = $orderCollection->getFirstItem();

Please Note:

Its not a good idea to load ALL the products/customers/orders for this takes a lot of resources. The preferred way is to limit what you want to load by using the addAttributeToFilter() or addFieldToFilter() functions, see example below:

$productCollection = Mage::getResourceModel('catalog/product_collection')
                           ->addAttributeToFilter('sku', 'book123`);