kmerge_deep

The kmerge_deep filter merges two arrays together recursively while preserving their keys (including numeric keys).

If the same array key exists in both arrays then the one in the second array will overwrite the first one.

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 replaced with the value in the second array.

If the value in the first array and second array are both arrays then the array values will be merged together while preserving their keys (including numeric keys).

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

{% set array = {1: 'One', 2: 'Two', 3: ['Three', 'Three is great'], 'four': 'Four string', 'five': {32: 'numeric key', 'string': 'string key'}} %}
{% set array2 = {2: 'New Two', 3: ['Another three'], 'four': 'New Four string', 'five': {32: 'new numeric key'}, 'six': 'I will stay'} %}
{% set array = array|kmerge_deep(array2) %}

The above will output:

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

Arguments

The kmerge_deep filter has the following signature.

kmerge_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