Get Smarty


Donate Bitcoin Bitcoin

Smarty Icon

You may use the Smarty logo according to the trademark notice.

Smarty Template Engine Smarty Template Engine

For sponsorship, advertising, news or other inquiries, contact us at:

Sites Using Smarty

Largest classified with thousands of ads at Shoppok

Buy cheap eyeglasses from and save up to 80%.

Buy prescription glasses from and save.

Cheap Glasses Now On Sale at Starts At $7.95.

Where to buy discount wedding dresses and cheap smart dresses free shipping -

Find Wedding Dresses Online at Canada from

Find your local domestic cleaner

Brautkleider auf

Find free files to download on

Looking For Affordable Wedding Dresses 2015 at Best Prices On

Shop high quality cheap prom dresses on

Buy New Arrival Cheap Prom Dresses 2015 at JDBRIDAL Prom Dress Store



{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: {$} with name being the name attribute.


    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.5. The item attribute

$arr = array(1000, 1001, 1002);
$smarty->assign('myArray', $arr);


Template to output $myArray in an un-ordered list

{foreach from=$myArray item=foo}


The above example will output:



Example 7.6. Demonstrates the item and key attributes

$arr = array(9 => 'Tennis', 3 => 'Swimming', 8 => 'Coding');
$smarty->assign('myArray', $arr);


Template to output $myArray as key/val pair, like PHP's foreach.

{foreach from=$myArray key=k item=v}
   <li>{$k}: {$v}</li>


The above example will output:

    <li>9: Tennis</li>
    <li>3: Swimming</li>
    <li>8: Coding</li>


Example 7.7. {foreach} with associative item attribute

$items_list = array(23 => array('no' => 2456, 'label' => 'Salad'),
                    96 => array('no' => 4889, 'label' => 'Cream')
$smarty->assign('items', $items_list);


Template to output $items with $myId in the url

{foreach from=$items key=myId item=i}
  <li><a href="item.php?id={$myId}">{$}: {$i.label}</li>


The above example will output:

  <li><a href="item.php?id=23">2456: Salad</li>
  <li><a href="item.php?id=96">4889: Cream</li>


Example 7.8. {foreach} with nested item and key

Assign an array to Smarty, the key contains the key for each looped value.

 $smarty->assign('contacts', array(
                             array('phone' => '1',
                                   'fax' => '2',
                                   'cell' => '3'),
                             array('phone' => '555-4444',
                                   'fax' => '555-3333',
                                   'cell' => '760-1234')


The template to output $contact.

{foreach name=outer item=contact from=$contacts}
  <hr />
  {foreach key=key item=item from=$contact}
    {$key}: {$item}<br />


The above example will output:

<hr />
  phone: 1<br />
  fax: 2<br />
  cell: 3<br />
<hr />
  phone: 555-4444<br />
  fax: 555-3333<br />
  cell: 760-1234<br />


Example 7.9. Database example with {foreachelse}

A database (eg PEAR or ADODB) example of a search script, the query results assigned to Smarty

  $search_condition = "where name like '$foo%' ";
  $sql = 'select contact_id, name, nick from contacts '.$search_condition.' order by name';
  $smarty->assign('results', $db->getAssoc($sql) );


The template which display None found if no results with {foreachelse}.

{foreach key=cid item=con from=$results}
    <a href="contact.php?contact_id={$cid}">{$} - {$con.nick}</a><br />
    No items were found in the search



index contains the current array index, starting with zero.

Example 7.10. index example

{* The header block is output every five rows *}
{foreach from=$items key=myId item=i name=foo}
  {if $ % 5 == 0}



iteration contains the current loop iteration and always starts at one, unlike index. It is incremented by one on each iteration.

Example 7.11. iteration and index example

{* this will output 0|1, 1|2, 2|3, ... etc *}
{foreach from=$myArray item=i name=foo}



first is TRUE if the current {foreach} iteration is the initial one.

Example 7.12. first property example

{* show LATEST on the first item, otherwise the id *}
{foreach from=$items key=myId item=i name=foo}
  <td>{if $}LATEST{else}{$myId}{/if}</td>



last is set to TRUE if the current {foreach} iteration is the final one.

Example 7.13. last property example

{* Add horizontal rule at end of list *}
{foreach from=$items key=part_id item=prod name=products}
  <a href="#{$part_id}">{$prod}</a>{if $smarty.foreach.products.last}<hr>{else},{/if}
  ... content ...



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}.

Example 7.14. total property example

{* show rows returned at end *}
{foreach from=$items key=part_id item=prod name=foo}
{if $}
  <div id="total">{$} items</div>
 ... something else ...


See also {section} and $smarty.foreach.

by René Pardon on Jan 23, 2012 at 3:54
Example 7.9. Database example with {foreachelse}
  $search_condition = "where name like '$foo%' ";
  $sql = 'select contact_id, name, nick from contacts '.$search_condition.' order by name';
  $smarty->assign('results', $db->getAssoc($sql) );
It is not secure to rely on the value of $foo, isn't it? I mean, why not using prepared statements or escaping? What happens if $foo contains sth. like: %'; SELECT * FROM .... regards
by bryan on Oct 23, 2011 at 10:47
for($i=0;$i<mysql_num_rows($result_total);$i++) { $result=Unserialize(mysql_result($result_total,$i,'packageDetail')); echo "<tr>" ; echo "<td bgcolor='#eeeeee' ><div align='center'><font color='#343434' face='Arial, Helvetica, sans-serif' size='2'>"; echo "<a href='PackageList.php?item=true&PackageName=".mysql_result($result_total, $i,"packageId")."'>"; echo mysql_result($result_total, $i,"packageName"); echo $result; echo "</a></font></div></td></tr>"; } }
Post a Comment
All comments are moderated. Support questions are ignored, use the forums instead.
Email: (not shown)
What is 1 plus 15? (Are you human?)


Sponsors [info]

UK Web Hosting
Best Web Hosting
Web Hosting UK
Unlimited Web Hosting
App Entwicklung
First Click Internet Marketing
Credit Card Processing Company
Cleaning Services Chicago