tags:

views:

520

answers:

4

I am looping through a nested array in smarty, and each element has a status of 'active' or 'inactive'. How can I detect the last element in the array that is set to active?

example code:

{foreach from=$steps item=step name=step}
 {if $step.status == 'active' && ????? }

 {/if}
{/foreach}
+1  A: 

Is the array indexed numerically or by key? If numeric i think the item argument in your loop is the index so you could use that in your if. if its not then youll have to call count to get the total number of items and then manually increment. or you could use array_values to transform the keys to numeric before starting your loop. Not really sure how to do any of that in Smarty though.

prodigitalson
A: 

I have no idea what "smarty" is, but the usual way to do this is to just keep a reference to the last element found; e.g.,

{foreach from=$steps item=step name=step}
    {if $step.status=="active" && ...}
        $last_step = $step
    {/if}
{/foreach}

Then, at the end of your loop, $last_step will be a reference to the last active $step. It you don't want the actual element, just its index, then save the index instead.

TMN
Smarty is a templating engine that supposedly has a purpose despite the fact that PHP itself is just a glorified templating engine (and i say this with a huge amount of love for PHP) :-)
prodigitalson
A: 

I think this is something, that goes outside template logic and should be done in script.

FractalizeR
A: 

Just use step parameter for foreach statement and use predefined variable $smarty.foreach.NAME.last

{foreach from=$steps item=step name=step_foreach}
    {if $step.status=="active" && $smarty.foreach.step_foreach.last}
        last step is active
    {/if}
{/foreach}
tenzor