Learn how you can append an item to an array in Twig (array_push way).

For a PHP developer, appending items to an existent array, is pretty easy as using array_push. Pitifully, a method or filter with the same name on Twig isn't available without a creating a custom extension, however you can achieve a good result using the merge filter.

Non associative arrays

If you original array isn't associative and you want append an item, ignoring the type of value, the merge filter expects as first argument an array whose content will be merged with the assigned variable:

{% set myArray = [] %}


{% set myArray = myArray|merge([1]) %}
{% set myArray = myArray|merge([2,3]) %}
{% set myArray = myArray|merge([4]) %}

{# 
    The content of myArray is
    myArray = [1,2,3,4] 
#}

Note that you can build any complex content using the same syntax:

{% set myArray = [] %}

{% set myArray = myArray|merge([
    [1,2],
    [3,4],
    [5,6]
]) %}

{% set myArray = myArray|merge([
    [
        [1,2]
    ],
    [
        [3,4]
    ],
]) %}
 
{# 
    The content of myArray is
    myArray = [
        [
            1,2
        ],
        [
            3,4
        ],
        [
            5,6
        ],
        [
            [1,2]
        ],
        [
            [3,4]
        ]
    ]
#}

Associative arrays

To add items to an associative array, you would only pass as first argument an array with brackets with the new values:

{# Note that the original array in this case has an item #}
{% set myArray = {
    "first": 1
} %}

{% set myArray = myArray|merge({
    "second": 2
}) %}

{% set myArray = myArray|merge({
    "third": 3
}) %}
 
{# 
    The content of myArray is
    myArray = {
        "first":1,
        "second":2,
        "third":3
    }
#}

Note that the merge filter uses array_merge in the background, which means that if you are working with an associate array, if the key already exists on the element it will be overwritten:

{# Note that the original array in this case has an item #}
{% set myArray = {
    "first": 1
} %}

{# Add the "second" key with value 2 #}
{% set myArray = myArray|merge({
    "second": 2
}) %}

{# Change the value of the "second" key#}
{% set myArray = myArray|merge({
    "second": "Modified 2"
}) %}
 
{# 
    The content of myArray is
    myArray = {
        "first":1,
        "second":"Modified 2"
    }
#}

Happy coding !


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors