phpsmarty3smarty2

index of array with smarty variables is not working


I have created array variable in .php file

like

$arImagePath[TE] = 'XYZ';

in my .tpl {$carnumber} is giving 'T' and {$carinitial} is giving 'E'.

I am trying to get value 'XYZ' as follows

{$arImagePath[{$carnumber}+{$carinitial}]}

I tried many combination still unavailable to get array value.

smarty version -2.6.26

Hoping for any help.


Solution

  • From documentation (Smarty v2) :

    {$foo[bar]} <-- syntax only valid in a section loop, see {section}

    So, if you want to access the array variable directly and you are not in a loop, you have to do it this way:

    {$foo.bar} <-- display the "bar" key value of an array, similar to PHP $foo['bar']


    Now, to archive what you need:

    // This assignment could change dynamically
    {assing var="carnumber" value="T"}
    {assing var="carinitial" value="E"}
    // For the sake of clarity, I'm going to concat in one variable the above assignments
    {assing var="index" value=$carnumber|cat:$carinitial}
    
    //Now access the array at the index we need
    {$arImagePath.$index} // XYZ