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 ?
{% 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 ...
Of course you could also skip arrayLength setter and use directly
{% for i in range(0, myarray|length - 1, 2) %}
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