Search code examples
phparrayssmarty

smarty grammar error cannot use symbol []


This line:

{$data["bank_data"]["Arrangement"]["id"]}

returns the following error:

PHP (5.3.9) ERROR (E_USER_ERROR):
File: Smarty.class.php
Line: 1092
Type: Smarty error: [in tke-g-admin_scopeofwork.tpl line 10]: syntax error: unrecognized tag: $data["bank_data"]["Arrangement"]["id"] (Smarty_Compiler.class.php, line 446)

This line:

{$data.bank_data.Arrangement.id}

does not return error. It works correctly.

So, why the first section is wrong? How to use [] to access array.


Solution

  • Judging from the error you posted, you're using Smarty2. The Docs give you two options for accessing arrays:

    {* for string indexes *}
    {$some.array.value}
    {* for numeric indexes *}
    {$some[0][1]}
    

    you can use a variable to provide an index like so

    {assign var="key" value="array"}
    {$some.$key.value} == {$some.array.value}
    

    using that "trick", you can also access string indexes containing "special characters" such as ., [] or .


    Smarty3 is a bit more flexible in that way:

    {$some.{"hello world"}.array["array"]['foo']}
    

    oddly enough {$foo[bar]} is not parsed properly (in Smarty 3.1.10). Threw that on the todo list, though.