Search code examples
foreachsmarty

How can stop foreach duplicate values in smarty 2?


I have this results after foreach on the template. But how can stop foreaching the same values and show only one?

<ul>
{foreach from=$names item=v name=thenames}
    <li>{$v.names}/<li>
{/foreach}
</ul>

Solution

  • If it's a simple key->value array, you can use array_unique in your php file to process the array before sending it to smarty. You also probably can call it inside the template with $names|array_unique

    If all the duplicates are one after another (i.e. a,a,a,b,b,c,c,c), you can try using a variable to store the previous value, so it only shows the first:

    {assign var="previous" value=""}
    {foreach from=$names item=v name=thenames}
        {if $previous!=$v.names}
        <li>{$v.names}/<li>
        {/if}
        {assign var="previous" value=$v.names}
    {/foreach}
    

    If not, I recommend preprocessing the array in php or using smarty 3.