10

Trying to output the index # of an array in twig, having trouble finding it in the docs. Anyone know how to get it?

array(2) {
  [0]=>
  array(2) {
    ["testimonial"]=>
    string(18) "Derby Heist Test 1"
    ["author"]=>
    string(6) "test 1"
  }
  [1]=>
  array(2) {
    ["testimonial"]=>
    string(18) "Derby Heist Test 2"
    ["author"]=>
    string(6) "test 2"
  }
}

so I'd like to output the index numbers 0 and 1 in a for loop. Please help.

Brendan Jackson
  • 305
  • 1
  • 3
  • 13
  • Possible duplicate of [Twig for loop and array with key](http://stackoverflow.com/questions/10299202/twig-for-loop-and-array-with-key) – HPierce Jan 24 '17 at 16:40

2 Answers2

17

You can use The loop variable as example:

{% for user in users %}
    {{ loop.index }} - {{ user.username }}
{% endfor %}

loop.index The current iteration of the loop. (1 indexed)

loop.index0 The current iteration of the loop. (0 indexed)

Hope this help

Matteo
  • 37,680
  • 11
  • 100
  • 115
  • Hi @BrendanJackson are you sure have accepted the correct answer at your question? I understand the correct answer was the `loop.index0`. Obviously is not a problem :) – Matteo Jan 26 '17 at 09:12
5

Just foreach through your main array, and specify you want the index:

foreach($array as $index=>$arr) { ...

$index will now give you what you need.

Or via TWIG:

{% for key,value in array_path %}
    Key : {{ key }}
    Value : {{ value }}
{% endfor %}
Stuart
  • 6,630
  • 2
  • 24
  • 40
  • I don't think this is how twig does it. – Brendan Jackson Jan 24 '17 at 16:09
  • Its just a regular php array don't forget (based on the var_dump you showed as an example) - try it, you may be pleasantly surprised. -- I have updated my answer to show how to access via twigs templating – Stuart Jan 24 '17 at 16:18
  • 2
    This should be the the accepted answer. While Matteos version will work in MOST times, it will not give the correct results for arrays with holes in them. – Emanuel Oster Jan 25 '17 at 15:34
  • 1
    I agree with @EmanuelOster, this answer is more solid. In my case, I had a multidimensional array that for some reason loop.index0 was reseted to 0 in each group. Using key solved my problem. Thanks. – Ricardo Castañeda Sep 13 '19 at 18:52