{foreach} is used to loop over an associative array as well a numerically-indexed array, unlike {section} which is for looping over numerically-indexed arrays only. The syntax for {foreach} is much easier than {section}, but as a tradeoff it can only be used for a single array. Every {foreach} tag must be paired with a closing {/foreach} tag.
Attribute Name | Type | Required | Default | Description |
---|---|---|---|---|
from | array | Yes | n/a | The array you are looping through |
item | string | Yes | n/a | The name of the variable that is the current element |
key | string | No | n/a | The name of the variable that is the current key |
name | string | No | n/a | The name of the foreach loop for accessing foreach properties |
Required attributes are from and item.
The name of the {foreach} loop can be anything you like, made up of letters, numbers and underscores, like PHP variables.
{foreach} loops can be nested, and the nested {foreach} names must be unique from each other.
The from attribute, usually an array of values, determines the number of times {foreach} will loop.
{foreachelse} is executed when there are no values in the from variable.
{foreach} loops also have their own variables that handle properties. These are accessed with: {$smarty.foreach.name.property} with "name" being the name attribute.
Note: The name attribute is only required when you want to access a {foreach} property, unlike {section}. Accessing a {foreach} property with name undefined does not throw an error, but leads to unpredictable results instead.
{foreach} properties are index, iteration, first, last, show, total.
Example 7-6. Demonstrates the item and key attributes
Template to output $myArray as key/val pair, like PHP's foreach.
The above example will output:
|
Example 7-7. {foreach} with associative item attribute
Template to output $items with $myId in the url
The above example will output:
|
Example 7-8. {foreach} with nested item and key Assign an array to Smarty, the key contains the key for each looped value.
The template to output $contact.
The above example will output:
|
Example 7-9. Database example with {foreachelse} A database (eg PEAR or ADODB) example of a search script, the query results assigned to Smarty
The template which display "None found" if no results with {foreachelse}.
|
iteration contains the current loop iteration and always starts at one, unlike index. It is incremented by one on each iteration.
show is used as a parameter to {foreach}. show is a boolean value. If FALSE, the {foreach} will not be displayed. If there is a {foreachelse} present, that will be alternately displayed.
total contains the number of iterations that this {foreach} will loop. This can be used inside or after the {foreach}.
See also {section} and $smarty.foreach.