Home » Php » php – Get index # of array in twig

php – Get index # of array in twig

Posted by: admin July 12, 2020 Leave a comment

Questions:

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.

How to&Answers:

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

Answer:

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 %}