Twitter Weekly Activity on 2009-07-12

July 12th, 2009

Powered by Twitter Tools.

Twitter Weekly Activity on 2009-07-06

July 5th, 2009

Powered by Twitter Tools.

Twitter Weekly Activity on 2009-06-28

June 28th, 2009

Powered by Twitter Tools.

Looping array in Smarty template engine

February 5th, 2009

A hint in looping an array in Smarty, is that when you use keys for your array is better to use foreach loop instead of section.

Smarty offers two ways of looping array variabiles:

section

php code:

$data = array(1000,1001,1002);
$smarty->assign('custid',$data);

smarty template file:

{* this example will print out all the values of the $custid array *}
{section name=customer loop=$custid}
  id: {$custid[customer]}
 
{/section}
<hr />
{*  print out all the values of the $custid array reversed *}
{section name=foo loop=$custid step=-1}
  {$custid[foo]}
 
{/section}

wil output:

id: 1000<br />
id: 1001<br />
id: 1002<br />
<hr />
id: 1002<br />
id: 1001<br />
id: 1000<br />

and foreach

php code:

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

template file:

<ul>
{foreach from=$myArray item=foo}
    <li>{$foo}</li>
{/foreach}
</ul>

output:

<ul>
    <li>1000</li>
    <li>1001</li>
    <li>1002</li>
</ul>

Well the big difference between them is that, section counts items from ascending i takest values from 0 to n-1, and if you have an array with 3 elements:

1
2
3
$array[10] = "value1";
$array[13] = "value2";
$array[100] = "value3";

and you loop it with Smarty {section loop=$array} you will have 3 itterations, but no values, because Smarty will try to print out values in the indexes: 0,1,2 so he will not reach effective indexes 10,13,100.

That’s why, if you use key relationing in your array, I recommend using foreach, wich acts exactly like the PHP foreach.