Search code examples
phparraysmultidimensional-arraysmarty3

multidimensional array in a custom smarty php plugin


When creating a custom smarty php plugin method, is it possible to pass in a multidimensional array as one of the params?

perhaps something like

{function title="Hi" options=array('opt1', 'opt2', 'opt3')}

The above is a sequential array, naturally support for an associative array would be equally as grand.

I've been scouring the docs and forums for hours but, unfortunately, everything I've been able to find has said "no" but has also been 5 years old (or more)

Thanks.


Solution

  • In Smarty3 you can.

    This examples uses PHP5.4 short array syntax, which replaces array() with []. Just use it like this:

    {function title="Hi" options=['opt1' => ['one' => 1], 'opt2' => ['two' => 2] ]}
    

    Another example: Assign to a variable and loop over it.

    {$multidimension_array = ['opt1' => ['one' => 1], 'opt2' => ['two' => 2] ]}
    
    {foreach $multidimension_array as $ak => $subarray}
        <p>Section "{$ak}":</p>
        <ol>
        {foreach $subarray as $k => $v}
            <li>{$k}: {$v}</li>
        {/foreach}
        </ol>
    {/foreach}
    

    Also, refer to the Smarty3 overview page where this syntax is exemplified.

    Note: PHP 5.4 is not required. This syntax is emulated at Smarty level.