loopsrandomsmartysmarty2

Generate distinct smarty random numbers


I'm using smarty v2.6 and I want to generate random distinct numbers. I'm looking for an efficient, fast way to do it using already provided Smarty functions. This is my code for generating 5 random numbers (but not distinct):

{assign var=min value=1}{assign var=max value =5}
{section name=val start=$min loop=$max+1}
{assign var=random value=1|mt_rand:15}
{$random}
{/section}

Solution

  • if you really need to do it in smarty templates

    method 1

    {assign var="distinct_numbers" value=array_fill(1,15,'x')}
    {assign var="distinct_numbers" value=array_keys($distinct_numbers)}
    {assign var="x" value=shuffle($distinct_numbers)}
    
    {* result *}
    
    {foreach from=$distinct_numbers item="value"}
        {$value} |
    {/foreach}
    
    
    1 | 7 | 3 | 10 | 4 | 8 | 6 | 14 | 13 | 12 | 2 | 5 | 11 | 9 | 15 | 
    

    method 2