Merge key and value into an array in Twig file

Sachin I picture Sachin I · Jun 30, 2015 · Viewed 7.3k times · Source

I want to add key and value into array in twig file. But I am facing following issue "Twig_Error_Syntax: A hash key must be a quoted string or a number"

{% set phoneCount = 0 %}
{% set phoneNumbers = {} %}
{% for currPhone in currBroker.phones %}
    {% if (currPhone.type == 'Work' or currPhone.type == 'Mobile') and phoneCount <= 2 and currPhone.number !='' %}
        {% set phoneCount = phoneCount + 1 %}                   
        {% set phoneNumbers = phoneNumbers|merge({ currPhone.type:currPhone.type }) %}
    {% endif %}
{% endfor %}
{{ phoneNumbers|print_r }}

I just need the syntax of merging key and value into array. I tried by giving static inputs and its works

{% set phoneNumbers = phoneNumbers|merge({ 'work':'(011)112-1233' }) %}

But its not working for dynmic input. Please help!!

Answer

Rapha&#235;l Mali&#233; picture Raphaël Malié · Jun 30, 2015

You have to wrap your key in braces :

{% set phoneNumbers = phoneNumbers|merge({ (currPhone.type) : currPhone.type }) %}

Tested and working example :

{% set currPhone = {type: 'test'} %}
{% set phoneNumbers = {} %}
{% set phoneNumbers = phoneNumbers|merge({ (currPhone.type) : currPhone.type }) %}
{% dump(phoneNumbers) %}

I get :

array:1 [▼
  "test" => "test"
]