82

I am looking to count the number of entries I have in an array in Twig. This is the code I've tried:

{%for nc in notcount%}
{{ nc|length }}
{%endfor%}

This however only produces the length of the string of one of the values in the array.

{{nc}} will produce an output of all the values of the array (there are 2) but I want the output to be just the number 2 (the count) and not all the information in the array.

Veve
  • 6,643
  • 5
  • 39
  • 58
MikeHolford
  • 1,851
  • 2
  • 21
  • 32

4 Answers4

171

Just use the length filter on the whole array. It works on more than just strings:

{{ notcount|length }}
Dharman
  • 30,962
  • 25
  • 85
  • 135
Paul
  • 139,544
  • 27
  • 275
  • 264
  • If `notcount` is not an array, but an object of a class implementing SPL Countable interface (this is the case of, for example, Doctrine's `\Doctrine\Common\Collections\ArrayCollection`), you can use `{{ notcount.count }}` – Quiquetas Jan 13 '21 at 20:26
6

This expands on the answer by Denis Bubnov.

I used this to find child values of array elements—namely if there was a anchor field in paragraphs on a Drupal 8 site to build a table of contents.

{% set count = 0 %}
{% for anchor in items %}
    {% if anchor.content['#paragraph'].field_anchor_link.0.value %}
        {% set count = count + 1 %}
    {% endif %}
{% endfor %}

{% if count > 0 %}
 ---  build the toc here --
{% endif %}
user3461392
  • 61
  • 1
  • 2
5

Best practice of getting length is use length filter returns the number of items of a sequence or mapping, or the length of a string. For example: {{ notcount | length }}

But you can calculate count of elements in for loop. For example:

{% set count = 0 %}
{% for nc in notcount %}
    {% set count = count + 1 %}
{% endfor %}

{{ count }}

This solution helps if you want to calculate count of elements by condition, for example you have a property name inside object and you want to calculate count of objects with not empty names:

{% set countNotEmpty = 0 %}
{% for nc in notcount if nc.name %}
    {% set countNotEmpty = countNotEmpty + 1 %}
{% endfor %}

{{ countNotEmpty }}

Useful links:

Denis Bubnov
  • 2,619
  • 5
  • 30
  • 54
0
{%for nc in notcount%}
{{ loop.index }}
{%endfor%}

loop.index -- The current iteration of the loop.

for reference:https://twig.symfony.com/doc/2.x/tags/for.html