I have a collection/array of ~4000 products(search results) and a category number and need to filter them.

What would be the most efficient way of checking whether a product belongs to a certain category?

Now I use:

foreach($products as $product) {
  $productCategories = $product->getAvailableInCategories();

  if(array_search($category, $productCategories) === false) {

  $filteredProducts[] = $product;   

$products may be an array or collection.

I would appreciate your input :).

$categoryIds = $product->getCategoryIds();
$isInCategory = in_array($category, $categoryIds);

If the $category variable is an object then do this:

$isInCategory = in_array($category->getId(), $categoryIds);
  • Thanks Marius! I will try this out and share my thoughts. – Alan Dec 5 '14 at 8:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.