Linked to these issues you previously closed :
https://github.com/twigphp/Twig/issues/1996?_pjax=%23js-repo-pjax-container
https://github.com/twigphp/Twig/issues/789
The issue is still here and there is currently no solution or workaround to get the expected behavior.
// variable declaration and affectation
{%
set array = {
0: 0,
1: 1
}
%}
array:2 [â–¼
0 => 0
1 => 1
]
// key value change (index 1 takes value 2)
{% set array = array|merge({(1): 2}) %}
// Expected behavior :
array:2 [â–¼
0 => 0
1 => 2
]
// Current behavior :
array:3 [â–¼
0 => 0
1 => 1
2 => 2
]
For a string name, the easiest solutions would be :
array["index"] = "value"
or
array.index = "value"
But they aren't working either, so it seems that Twig doesn't support that much for arrays.
The only solution someone founds would be to change integer key to string key by this way :
{% set temp= temp|merge({(key~'_'):value}) %}
But like I previously commented inside the closed issue's comments, you can't expect every developer having this issue that they'll change numerical key to string key.
You are actually providing no function to easily modify the value of an array key.
That's exactly the behavior of array_merge. Twig has hashes and lists in its syntax, but they both map to PHP arrays, so we cannot have our merge filter being smart about deciding whether you want to merge lists or maps (i.e. switching between array_merge and array_replace smartly.
Numeric keys in arrays treated as a map are indeed not working well with the existing merge filter
The issue is still here and there is currently no solution or workaround to get the expected behavior.
@TyrionGraphiste, you can use the + (union) array operator: {% set array = {(1): 2} + array %} https://twigfiddle.com/vbideu
Most helpful comment
@TyrionGraphiste, you can use the
+(union) array operator:{% set array = {(1): 2} + array %}https://twigfiddle.com/vbideu