Simplifying complex {if}{else} statements in {foreach} loops

Do something cool with CMS? Show us ...
This board is for 'Answers', and the discussion of answers... Not for questions.
Post Reply
psy
Power Poster
Power Poster
Posts: 463
Joined: Sat Jan 22, 2005 11:19 am

Simplifying complex {if}{else} statements in {foreach} loops

Post by psy »

An easy way to exclude items is to put one {if} conditional statement, an action and close the {/if} at the beginning of the loop, eg:

Code: Select all

{foreach from=$items item='entry'}
{if $entry == 'something' || or $entry < 15} 
  {continue}
{/if}
<p>do whatever with all the other entries.</p>
{/foreach}
Then when the loop encounters an entry that meets the condition, it immediately moves on to the next entry.

You can also shorten {foreach} processing times by making the loop stop once it meets the first instance of a condition, eg:

Code: Select all

{foreach from=$items item='entry'}
{if $entry == 'something' }
  <p>Hello {$entry}</p>
  {break} 
{/if}
{/foreach}
Post Reply

Return to “Tips and Tricks”