Associative Array Keys
| From: | Duncan Forrest | Date: | Mon, 14 Jan 2002 14:16:48 +0000 |
| Subject: | Associative Array Keys | ||
| Groups: | php.smarty.general | ||
| Request: | Send a blank email to php-smarty-general+get-2532@lists.php.net to get a copy of this message | ||
Hi
I was wondering whether it's possible to access an element of an
associative array without hard-coding the element's key into the
template. To illustrate with an example, say I have the following
PHP code:
$copy["foo"] = "This is foo";
$copy["bar"] = "This is bar";
$which = "foo";
$smarty->assign("copy", $copy);
$smarty->assign("which", $which);
I have no problem inserting strings at various points in my template
using {$copy.foo} or {$copy.bar}, but in some instances I don't until
my PHP code has executed which of the elements of $copy I actually
want, so I'd like to be able to access what in PHP would be
$copy[$which]. I tried the following in a template as a test:
which is ^{$which}^<br>
copy.foo is ^{$copy.foo}^<br>
copy.bar is ^{$copy.bar}^<br>
copy.$which is ^{$copy.$which}^<br>
and as a complete fudge:<br>
copy[$which] is ^{$copy[$which]}^<br>
but that yields:
Warning: Smarty: [in profile.html line 8]: syntax error: unknown tag -
'$copy.$which' in Smarty/Smarty_Compiler.class.php on line 1182
Warning: Smarty: [in profile.html line 9]: syntax error: unknown tag -
'$copy[$which]' in Smarty/Smarty_Compiler.class.php on line 1182
which is ^foo^
copy.foo is ^This is foo^
copy.bar is ^This is bar^
copy.$which is ^^
and as a complete fudge:
copy[$which] is ^^
So, my question boils down to this:
* Is there an easy way to access $copy[$which] in the template that
I'm missing?
I know I could always use a {foreach} loop and examine each key for
equality to $which, but that's a far more complex structure than I
want when I'm just after a single isolated element of the array.
To put it in context, I'm writing a multilingual app which stores
every piece of English (or whatever) copy in a database. The PHP
populates the $copy array with all the phrases I need in whatever
language and so my templates are peppered with {$copy.foo} or
{$copy.bar} references all over the place. On pages which also
include error messages, I don't know what the error will be until my
PHP code has set a variable named $err. Since I can't access
$copy.$err, I'm currently assigning an extra variable, like this:
if ($err) $smarty->assign("err", $copy[$err]);
but that means whichever error string I end up using actually gets
assigned twice, once as part of $copy and once as $err. That doesn't
seem too wasteful in this example, but in other areas it's led to me
re-assigning some big multi-dimensional arrays.
Regards,
Duncan Forrest