The problem is very short.
I have got an array with integer keys, and parameter which is the string. I want to get element of that array by using that parameter.
How to get in Twig intval - (int)"32"
of {{ variable }}
where variable == (string) "32";
?
There are filters in twig. One of them is this:
https://twig.symfony.com/doc/2.x/filters/number_format.html
{{ variable|number_format }}
if you are doing math on a string, it will automatically cast to an interger anyways, however!
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
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With