1

I would like to access alternate elements in an array using its index.
Something like this :

for(i=0;i<count(myarray);i++)
{
print myarray[i+1];
}

How can I do this with twig ?

2 Answers 2

3
{% set arrayLength = myarray|length - 1 %}

{% for i in range(0, arrayLength, 2) %}
    {{ myarray[i] }}
{% endfor %}

This should print this elements: myarray[0], myarray[2], myarray[4], and so on ...

Explaination

  1. Set a variable arrayLength to keep number of array's element. We need to set it one unit behind the "real" count as array is zero-indexed
  2. Loop in range from 0 to arrayLength (count - 1 as explained above) with a 2 step (third argument stands for "increase index of n each step"; in this case "n" is 2)
  3. Print the result

Of course you could also skip arrayLength setter and use directly

{% for i in range(0, myarray|length - 1, 2) %}
Sign up to request clarification or add additional context in comments.

Comments

1

I prefer from far the DonCallisto Answer, but for diversity of answers here is one other...

Context :

myarray:
    - a
    - b
    - c
    - d
    - e
    - f
    - g
    - h

Twig :

{% for key, value in myarray if not key % 2 %}
    {{ value }}
{% endfor %}

Results :

a
c
e
g

TwigFiddle : http://twigfiddle.com/hmzuye

1 Comment

This is also a good one and I love when users try to give an alternative to OP.

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.