0

I have the following array and i want to access the value of a specified element with twig.

numbers => Array ([01234567] => Array ( [0] => 9876543210 [1] => 8765432109 [2] => 0000000000))

I know there is only one entry in numbers, so I want to access the array with the key 01234567 directly.

Even tough numbers|keys[0] does return the correct key, I can't use it like numbers[numbers|keys[0]] to get the array. I also tried the attribute(array, item) function, but i didn't got it to work.

Is it possible to access it directly or do I need to use loops?

3
  • Not sure I understand your question. Does the current function work? php.net/manual/en/function.current.php Commented Jan 17, 2013 at 20:08
  • Is it possible to use php functions in twig templates? Commented Jan 17, 2013 at 20:14
  • It is, if you write a custom twig extension, but that's probably not what you want Commented Jan 17, 2013 at 20:15

1 Answer 1

1

You have found a probably undocumented "feature" of Twig. If you check the source code, twig tries to determine if the given key is numeric, or not. It does this check with the ctype_digit function, which checks if a variable contains only numeric characters.

The example in your question contains an array key, which meets this conditions: it contains only numbers. Unfortunately, it also starts with a zero, which is removed when the string is converted into an integer.

I'm not exactly sure that this is intended behavior, so you may try to report this example as a bug.

For the current twig implementation, because everything except the loop construct uses the getAttribute function, you have no other choice but to use a for loop.

Sign up to request clarification or add additional context in comments.

3 Comments

Does this work for you? For me it doesn't, when I use {{array_item}} it doesn't show anything.
wow, twig removes the first zero from the number, I haven't expected this, even when I force a string concatenation (e.g. {% set array_item = numbers[index_var] %} still generates an exception)
Thanks for your efforts, i am going to report it "tomorrow".

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.