So I've read all the posts and followed along at home. I'm not a CS major. I have an array:

{% set testArray = {
  name: "John Doe",
  email: "[email protected]",
  players: [
    playerName: "Jane Doe",
    PID: 8885551212,
    TID: 1234,
    playerName: "Billy Doe",
    PID: 8285551,
    TID: 1222,
follows : [

Great, it verks!! When I ask it to spit it out via: {{testArray|json_encode}}, it spits out:

{"name":"John Doe","email":"[email protected]","players":[{"playerName":"Jane Doe","PID":8885551212,"TID":1234},{"playerName":"Billy Doe","PID":8285551,"TID":1222}],"follows":["234","345","999"]}

Huzzah, go me!

Now, if I want to update the players array, I'm trying this

{% set testA = { playerName:"Henry Doe",PID: 8885551333,TID: 1} %}
{% set testArray = testArray|merge({ "players": [testA]} ) %}

It'a good boi and does this BUT it overwrites the other 2 objects in the array and outputs

{"name":"John Doe","email":"[email protected]","players":[{"playerName":"Henry Doe","PID":8885551333,"TID":1}],"follows":["234","345","999"]}

So, the question is A) is it even possible? b) WTAF am I doing wrong?

1 Answer 1


The merge filter only does a shallow merge. This means that if both the first and the second hash (in Twig, an associative array is called a hash) have the same key, the final result will contain just the value of the second array. What you're looking for is a deep merge, which will recursive merge nested arrays and hashes.

Luckily, Craft extends Twig's merge filter to support a deep merge. Pass true as a second argument and the filter will perform a deep merge.

{% set newPlayer = { playerName: "Henry Doe", PID: 8885551333, TID: 1} %}
{% set testArray = testArray|merge({ players: [newPlayer], }, true) %}

As a sidenote, Twig isn't really designed or intended for this type of complex data manipulation. In most cases, you should do this in PHP – you can find examples of how to extend Twig with PHP functions here: https://craftcms.com/docs/4.x/extend/extending-twig.html

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.