Magento – How to check if a collection has items

category-productsmagento-1.9PHP

What does a product that is not found return in terms of Object?

I'm loading a product like the following:

$man_collection = Mage::getModel('catalog/category')
    ->load($mProduct)
    ->getProductCollection()
    ->addAttributeToSelect('*')
    ->addAttributeToFilter('status', 1)
    ->addAttributeToFilter('visibility', 4)
    // ->getSelect()->limit(1);
    ->addFieldToFilter(array(
        array('attribute' => 'color', 'eq' => '1049')
    ));

Assuming that this specific product with this color code 1049 does not exist in the database, how can I validate it? If I try

gettype($man_collection)

it still returns Object. So is there a way to validate this? Like "if product with color code 1049 found proceed, else echo not found"

Best Answer

You can check the size of your collection:

if ($man_collection->getSize()) {
    //proceed
} else {
    echo "not found";
}

Explaination here: Difference between getSize() and count() on collection


Edit: tested for 750 products

$collection->getData()

  • Total Incl. Wall Time (microsec): 67,567 microsecs
  • Total Incl. CPU (microsecs): 67,599 microsecs
  • Total Incl. MemUse (bytes): 11,719,168 bytes
  • Total Incl. PeakMemUse (bytes): 11,648,152 bytes
  • Number of Function Calls: 1,047

$collection->getSize()

  • Total Incl. Wall Time (microsec): 6,371 microsecs
  • Total Incl. CPU (microsecs): 4,402 microsecs
  • Total Incl. MemUse (bytes): 140,816 bytes
  • Total Incl. PeakMemUse (bytes): 96,000 bytes
  • Number of Function Calls: 191

$collection->count() or sizeof($collection)

  • Total Incl. Wall Time (microsec): 2,130,568 microsecs
  • Total Incl. CPU (microsecs): 2,080,617 microsecs
  • Total Incl. MemUse (bytes): 12,899,872 bytes
  • Total Incl. PeakMemUse (bytes): 13,002,256 bytes
  • Number of Function Calls: 101,073