2
{% set var_name1 = "hello" %}
{% set var_name2 = "there" %}
{% array1|merge({var_name1: var_name2}) %}

I was hoping the code above would add this to array1:

hello:there

...but it adds:

var_name1:there

I've tried wrapping {{ }} around var_name1. Is it possible to add a record to an array and use a variable for the key?

2 Answers 2

10

Enclose the key name in brackets:

{% array1|merge({(var_name1): var_name2}) %}
Sign up to request clarification or add additional context in comments.

Comments

2

Note that if var_name1 is a numeric value, it won't work. You'll have to concat it with a string value :

{% set array1 = array1|merge({(var_name1~'_'): var_name2}) %}

1 Comment

Here is an explanation in a twig issue: github.com/twigphp/Twig/issues/2741 - merge is basically array_merge with all it's behavior. (numeric keys are renumbered!)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.