How to access key and value of an array in smarty template? – Smarty

Photo of author
Written By M Ibrahim
arrays cakephp foreach smarty

Quick Fix: Within Smarty templates, you can access a key-value pair using a foreach loop with the key variable providing the key and the item variable providing the value.

The Problem:

A developer is having trouble accessing the key and value of an array named $enquiries_labels in a Smarty template file. The array is assigned from a PHP file and contains values such as ‘New Enquiry’, ‘Retail Enquiry’, ‘Feedback’, etc. The developer wants to use a foreach loop to generate HTML options for a select control, and needs to set the ‘selected’ attribute for any option whose key matches a pre-selected value from the PHP file. However, the code the developer tried, which is included in the question, is not working as expected.

The Solutions:

Solution 4: {title}

One can access the key and value of an array in a Smarty template using the `@key` and `@value` modifiers. For example:

{foreach $products as $product}
    key: {$product@key} -> value: {$product@value}
{/foreach}

This will output:

key: 0 -> value: Product 1
key: 1 -> value: Product 2
key: 2 -> value: Product 3

One can also use the `@key` and `@value` modifiers to access the key and value of an array within a loop. For example:

{foreach $products as $key => $value}
    key: {$key} -> value: {$value}
{/foreach}

This will output:

key: 0 -> value: Product 1
key: 1 -> value: Product 2
key: 2 -> value: Product 3

Additionally, one can access the key and value of an array using the `foreach from` tag:

{foreach from=$products item=product key=key}
    key: {$key} -> value: {$product}
{/foreach}

This will output:

key: 0 -> value: Product 1
key: 1 -> value: Product 2
key: 2 -> value: Product 3