TEKA
TEKA

Reputation: 23

How to display an array in smarty?

I want to produce an array result like this ['element1','element2','element3'] with smarty. I am working with PHP and smarty. The array is generated from PHP and then outputted by smarty in the above format or style. My PHP code is like this:

$countries = array('America','Germany','Japan');

I want to display the same array content in Smarty but this time the result should be displayed as this in smarty

['America','Germany', 'Japan']

Could anyone be of help to me? Thanks!

Upvotes: 2

Views: 1341

Answers (1)

kushalbhaktajoshi
kushalbhaktajoshi

Reputation: 4678

Check foreach loop here
PHP CODE

$countries = array('America','Germany','Japan');
$smarty->assign('countries', $countries);

SMARTY CODE

[
{foreach from=$countries item=country}
    {assign var='total' value=$countries|@count}         {* This stores the total no. of elements in COUNTRIES array in TOTAL variable *}
    {counter assign="count"}                             {* This assigns a counter to COUNT variable *}
    '{$country}'
    {if $count lt $total}
    ,                                                    {* This condition adds ',' after each element of the array until and unless the loop reaches the last element. When the last element reached, this condition won't add ',' *}
    {/if}
{/foreach}
]

Upvotes: 6

Related Questions