foreach

Summary

Iterates over arrays in different ways.

Usage

{foreach <array> as [ $keyVar => ] $itemVar  
         [ sequence <array> as $sequenceVar ]
         [ offset <offset>                  ]
         [ max <max>                        ]
         [ reverse                          ]}

    [ {delimiter}...{/delimiter} ]
    [ {break}    ]
    [ {continue} ]
    [ {skip}     ]
    
{/foreach}

Description

This construct makes it possible to iterate over arrays in different ways. The loop can be tweaked using parameters:

Parameter

Description

Value

sequence

Defines a sequence which is iterated together with the normal loop parameter (see example below)

array

offset

Determines the start of the loop array for the iterations

integer

max

Determines the maximum number of iterations

integer

reverse

The loop is performed in the reverse order if this is set

 

There are also a set of inline template loop control structures available, these need to be a direct child of the foreach structure:

 

Description

Value

delimiter

Determines a block of template elements which should be placed in between two iterations

mixed

skip

Jumps to next iteration, does NOT output delimiter

 

breaks

Breaks out of the foreach

 

continue

Jumps to next iteration, but outputs delimiter

 

Examples

Example 1

{foreach $objects as $object}
 
    {$object.name} <br />
 
{/foreach}

This example will print out the names of the objects that are stored in the $objects array. If this array stores 4 objects with the following names: "Emmett Brown", "Marty McFly", "Lorraine Baines" and "Biff Tannen", the following output will be produced:

Emmett Brown
Marty McFly
Lorraine Baines
Biff Tannen

Example 2

{foreach $objects as $index => $object}
 
    {$index} : {$object.name} <br />
 
{/foreach}

This example demonstrates how to create an iteration counter.

0: Emmett Brown
1: Marty McFly
2: Lorraine Baines
3: Biff Tannen

Example 3

{foreach $objects as $object sequence array( 'dark', 'light' ) as $style}
 
    <div class="{$style}">{$object.name}</div>
 
{/foreach}

This example demonstrates how to create a loop where the iterations are displayed using alternating styles (in this case dark, light, dark, light and so on).

Powered by eZ Publish™ CMS Open Source Web Content Management. Copyright © 1999-2013 eZ Systems AS (except where otherwise noted). All rights reserved.