|
Smarty
WARNING: All discussion is moving to https://reddit.com/r/smarty, please go there! This forum will be closing soon. |
|
View previous topic :: View next topic |
Author |
Message |
gawan Smarty Rookie
Joined: 29 Apr 2003 Posts: 9
|
Posted: Mon Aug 11, 2003 9:43 pm Post subject: use of 'key' in a foreach loop? |
|
|
I don't quote get it where I should (or could) use the 'key' parameter in a foreach loop. Most of the time it makes no difference if I leave it out (I am looping mainly through arrays from a database). Can someone clarify this to me, please? |
|
Back to top |
|
messju Administrator
Joined: 16 Apr 2003 Posts: 3336 Location: Oldenburg, Germany
|
Posted: Mon Aug 11, 2003 9:57 pm Post subject: |
|
|
if you don't need it, don't declare it. "from" and "item" are mandatory, but "key" is optional. |
|
Back to top |
|
boots Administrator
Joined: 16 Apr 2003 Posts: 5611 Location: Toronto, Canada
|
Posted: Mon Aug 11, 2003 10:00 pm Post subject: |
|
|
Associative arrays have two portions for each element in the array: 1) the unique key (name, if you wish) of the element and 2) the item that the element is representing. Smarty allows you to refer to either (or both) portions by using the appropriate item/key parameters of {foreach}.
As a simple example, if you have an associative array like:
[php:1:da4f971ecc]<?php
$smarty->assign('test', array('el1' => 'element 1'));
?>[/php:1:da4f971ecc]
with template code like:
Code: | {foreach from=$test item=i key=k}
{$i}
{/foreach} |
your resulting output would be element1.
Whereas the template code:
Code: | {foreach from=$test item=i key=k}
{$k} : {$i}
{/foreach} |
produces el1 : element1.
The key is optional for the cases where you don't care about the associated key value for the current item.
An array doesn't need to be strictly associative to be used with {foreach}. For example, if you want to iterate an array of lines from a file, then only the element portion of each item is relevant and you can omit the key portion.
[php:1:da4f971ecc]<?php
$smarty->assign('test', file('some.text.file'));
?>[/php:1:da4f971ecc]
with template code like:
Code: | {foreach from=$test item=line}
{$line}<br/>
{/foreach} |
as you should expect, you will end up with a reproduction of your text file.
If you are still uncertain, you may want to review the section on arrays in the PHP manual.
HTH |
|
Back to top |
|
gawan Smarty Rookie
Joined: 29 Apr 2003 Posts: 9
|
Posted: Thu Aug 14, 2003 6:43 am Post subject: |
|
|
Thank you boots |
|
Back to top |
|
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum
|
Powered by phpBB © 2001, 2005 phpBB Group
|