merge_deep

The merge_deep filter merges two arrays together recursively.

If the same array key exists in both arrays and the key is not a number, then the one in the second array will overwrite the first one.

If the same array key exists in both array and the key is a number then the value in the second array will be appended to the first.

If a key exists in the second array but not in the first array, then it will be added to the first array.

If a key only exists in the first array then it will be left as it is.

If the value in the first array is not an array then it will be converted to an array and the value in the second array will be merged with it.

If the value in the first array and second array are both arrays then the array values will be merged.

The merge is recursive so the same process will be applied to inner arrays.

If you need the array keys preserved then use the kmerge_deep filter.

{% set array = {1: 'One', 2: 'Two', 3: ['Three', 'Three is great'], 'four': 'Four string', 'five': {32: 'numeric key', 'string': 'string key'}} %}
{% set array2 = {1: 'One2', 2: 'Two2', 4: 'Four', 5: 'Five'} %}
{% set array = array|merge_deep(array2) %}

The above will output:

Array
(
    [0] => One
    [1] => Two
    [2] => Array
        (
            [0] => Three
            [1] => Three is great
        )
    [four] => Array
        (
            [0] => Four string
            [1] => New Four string
        )
    [five] => Array
        (
            [32] => numeric key
            [string] => string key
            [33] => new numeric key
        )
    [3] => New Two
    [4] => Array
        (
            [0] => Another three
        )
    [six] => I will stay
)

Arguments

The merge_deep filter has the following signature.

merge_deep(array)

Argument Description
array

The array value to merge with the first array.

It can be a numeric array or a hash (associative array) or a combination of the two.

< Back to the list of filters