1

I'm creating a list of products, which is filtered to only show products within certain categories in Magento. I'm using the AddAttributeToFilter which is working fine:

$products->addAttributeToFilter('category_id', array('in' => array(105,106)));

This seems to work fine and it retrieves products that are in category 105 and 106.

However, I'm building a form that will dynamically pass the IDs into the filter depending on a user's selection. So in some case there will only be 2 category IDs, other times there maybe 6 different category IDs.

For example:

$products->addAttributeToFilter('category_id', array('in' => array(105,106,124,158,147)));

However, I can't figure out how I can create the array dynamically.

I tried this but it doesn't work:

$val = "105,106,124,158,147";
$products->addAttributeToFilter('category_id', array('in' => array('$val')));

Any help would be much appreciated.

1 Answer 1

1

What you tried isn't an array, but a string.

Try this instead:

$val = "105,106,124,158,147";
$val_array = explode(",", $val);
$products->addAttributeToFilter('category_id', array('in' => array($val_array)));

The explode command will split the string by the comma and produce an array for it.

2
  • Wow, thanks that was super fast! Tried it out and it works perfectly. Thanks again.
    – Nicholas
    Commented Feb 3, 2015 at 13:36
  • No problem, glad to help :)
    – Dan Hanly
    Commented Feb 3, 2015 at 13:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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