How to use Smarty foreach?

21 Sep

How to use Smarty foreach?

You can pass an array to the smarty tpl file as shown below.

<?php
$user_details = array(
	"name" => "x",
	"address" => "Y",
        "phone" => "Z"
);
$smarty->assign('my_array', $user_details);  //my_array can be replaced with anything

Then in the tpl file you can loop through the array as shown below

<ul>
{*    
   Note: We used my_array here because we passed array as
   assign('my_array', $user_details);
*}

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

If we are passing an array without key in it say

$user_details = array(
	"x", "y", "z"
);
$smarty->assign('my_array', $user_details); 

Then we can display the values in the tpl as shown below

<ul>
{foreach from=$my_array item=v}
   <li>{$v}</li>
{/foreach}
</ul>

Leave a Reply

Your email address will not be published. Required fields are marked *