10

How can I check the current iteration for foreach and do something?

{foreach $new_products as $product name=foo}
    {if $smarty.foreach.foo.iteration=5}
        Do it!
    {/if}
{/foreach}

This always return not checked

Marcio Mazzucato
  • 8,841
  • 9
  • 64
  • 79
skywind
  • 892
  • 6
  • 22
  • 44

3 Answers3

11

I think you should do {if $smarty.foreach.foo.iteration == 5} (note the ==).

apfelbox
  • 2,625
  • 2
  • 24
  • 26
  • Why the double equals? Just trying to understand because === works fine too. – jagershark Aug 13 '15 at 07:53
  • @loxyboi you can use two or three equal signs (three will check, that the type matches, too – see http://php.net/manual/de/language.types.type-juggling.php). But in the original question there were only one equal sign, which is wrong. – apfelbox Aug 13 '15 at 09:24
  • @apfelbox oh yeah I can see that now, didn't spot the one '=' in the question. Thought you were referring to smarty specific rules. Thanks! – jagershark Aug 13 '15 at 11:17
6

There is an alternative (I think newer) technique for this. The example from the Smarty docs demonstrates it nicely:

{foreach $items as $i}
  {if $i@index eq 3}
     {* put empty table row *}
     <tr><td>nbsp;</td></tr>
  {/if}
  <tr><td>{$i.label}</td></tr>
{/foreach}

Note the index starts from zero, so index 3 is the 4th iteration.

Highly Irregular
  • 38,000
  • 12
  • 52
  • 70
4

For Smarty 3 you can use the @iteration property

{foreach $new_products as $product}
    {if $product@iteration == 5}
        Do it!
    {/if}
{/foreach}
Marcio Mazzucato
  • 8,841
  • 9
  • 64
  • 79