You can access a value of an array using a variable as the key like this: myArray[myKey]
. It doesn't matter whether the array keys are integers (e.g. 32
) or corresponding strings ("32"
), or whether myKey
is an integer or a string. All of these combinations should work (see TwigFiddle):
{% set myArray = {
1: 'first',
'2': 'second',
} %}
{% set keyOneInt = 1 %}
{% set keyOneStr = '1' %}
{% set keyTwoInt = 2 %}
{% set keyTwoStr = '2' %}
{# These all print 'first' #}
{{ myArray.1 }}
{{ myArray[1] }}
{{ myArray['1'] }}
{{ myArray[keyOneInt] }}
{{ myArray[keyOneStr] }}
{# These all print 'second' #}
{{ myArray.2 }}
{{ myArray[2] }}
{{ myArray['2'] }}
{{ myArray[keyTwoInt] }}
{{ myArray[keyTwoStr] }}
On the third line of the above code, the string key '2'
is actually cast to integer 2
, like PHP's documentation of arrays states:
Strings containing valid decimal integers, unless the number is
preceded by a + sign, will be cast to the integer type. E.g. the key
"8" will actually be stored under 8. On the other hand "08" will not be
cast, as it isn't a valid decimal integer.
If for some reason you need an integer, you can cast a string to an int by performing math operations on it – e.g. variable * 1
(= "32" * 1
) or variable + 0
(= "32" + 0
).