Search code examples
phpprestashopsmarty

How to loop over an array in Smarty/Prestashop?


I use this code in Prestashop

{if (strpos($product.name, 'TVNUMBER1') !== false)}
    THIS PRODUCT IS IN SALE
{/if}

So whenever I want to display that certain products are in sale, I have to go line by line, specifying the same product i.e."TVNUMBER1". I want to be able to write an array detailing all the products I have in sale "TV1, TV2, TV3", and get a code like this:

{if (strpos($product.name, '$array') !== false)}
    THIS PRODUCT IS IN SALE
{/if}

I've tried similar examples found here, but I can't get them to work, either in Prestashop or in PHP testers online. It looks super simple, but I can't get around it.


Solution

  • I think what you want is the in_array php function, that check if a given $needle is or not in an array.

    So what you should do is :

    {if (in_array($product.name, '$array') !== false)}
        THIS PRODUCT IS IN SALE
    {/if}
    

    Then in your controller you can assign the array to smarty :

    $arr = array('TVNUMBER1', 'TVNUMBER2', 'TVNUMBER3');
    $smarty->assign('myArray', $arr);