Smarty how to get a first index from foreach?

Marius picture Marius · Dec 27, 2012 · Viewed 22k times · Source

Construction is this:

<!-- projects list -->
            {if !empty($userObjects)}
                <select id="projects-list" tabindex="1" name="project">
                    {if !isset($selected)}<option value="0">Choose project</option>{/if}
                {foreach from=$userObjects item=v}
                    <option value="{$v.Id}" {if $selected==$v.Id}selected="selected"{/if} }>{$v.Name}

                        {* if it's 1st element *}
                        {if $smarty.foreach.v.index == 0}
                            {if isset($limit)}<br /><span id="projlimit">{$limit}</span> {$currency->sign}{/if}
                        {/if}

                    </option>
                {/foreach}
                </select>

as you can see I did

{if $smarty.foreach.v.index == 0}

but it's going wrong. In this case all the options elemets has a $limit value. How to make it good? I need only first one.

Answer

hdvianna picture hdvianna · May 10, 2013

I don't want to appear rude, but Bondye's answer will not work in all cases. Since PHP's arrays are ordered maps, the value of the first key will not always be 0.

In these cases you can use the @index, @iteration or @first properties. More details are in the smarty foreach documentation at http://www.smarty.net/docs/en/language.function.foreach.tpl#foreach.property.iteration

One of the possible solutions to your question is bellow:

{foreach $rows as $row}
    {if $row@iteration == 1}
        First item in my array          
    {/if}            
{/foreach}