PHP Dynamic Values in Array – How to Pass

arrayPHP

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.

Best Answer

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.

Related Topic