Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intval in Twig Template

Tags:

twig

symfony

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";?

like image 279
user3383675 Avatar asked Sep 07 '25 01:09

user3383675


2 Answers

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!

like image 119
ToBe Avatar answered Sep 09 '25 01:09

ToBe


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).

like image 26
Matias Kinnunen Avatar answered Sep 09 '25 03:09

Matias Kinnunen