<p>Before we proceed, let me say that whilst the following will work, I personally think this is a poor use of Twig.</p>

<p>It's far better to collate this information in a simple plugin, rather than jumping through such hoops in your templates.</p>

<p>Caveats dispensed with, here you go:</p>

<pre><code>{% set criteria = {
    section: 'exampleSection',
    limit: 20,
    with: ['categoryFieldHandle']
} %}

{% set categories = {} %}
{% set entries = craft.entries(criteria).find() %}

{% for entry in entries %}
    {% set entryCategories = entry.categoryFieldHandle %}
    {% if entryCategories|length %}
        {% for entryCategory in entryCategories %}
            {% set categorySlug = entryCategory.slug %}

            {% if categories[categorySlug] is not defined %}
                {% set categories = categories|merge({
                    (categorySlug): {
                        count: 0,
                        category: entryCategory
                    }
                }) %}
            {% endif %}

            {% set categoryCount = attribute(categories, categorySlug)['count'] + 1 %}

            {% set categories = categories|merge({
                (categorySlug): {
                    count: categoryCount,
                    category: entryCategory
                }
            }) %}
        {% endfor %}
    {% endif %}
{% endfor %}

{% if categories|length %}
    &lt;h2&gt;Category Counts&lt;/h2&gt;
    &lt;ul&gt;
        {% for categoryKey, categoryInfo in categories %}
            &lt;li&gt;{{ categoryInfo.category.title }}: {{ categoryInfo.count }}&lt;/li&gt;
        {% endfor %}
    &lt;/ul&gt;
{% endif %}
</code></pre>

<p>Note that we're <a href="https://craftcms.com/docs/templating/eager-loading-elements" rel="nofollow noreferrer">eager loading</a> the categories. Otherwise, we'll end up with N+1 queries.</p>

CC BY-SA 3.0
2017-02-20T20:12:35.670Z
Thanks a lot! I will look into plugins then and start with this
mstoldt
CC BY-SA 3.0
2017-02-20T21:19:33.953Z
Sounds good. You can translate the above approach to PHP pretty easily.
Stephen Lewis
CC BY-SA 3.0
2017-02-20T17:04:02.170Z
2017-02-20T17:04:02.170Z
Stephen Lewis
<p>I am having entries in a Craft channel-section. Each entry has the field "type" with one category filled. I need to iterate through the entries and count the amount of each category.</p>

<p><strong>Example:</strong></p>

<pre><code>Entry 1, Category: One
Entry 2, Category: One
Entry 3, Category: Two
</code></pre>

<p>Produces something like</p>

<pre><code>One: 2, Two: 1
</code></pre>

<p>So I know which category is used how often. In any language I would use a key/value set and just increment the amount each time I find the specific category, but that seems to be impossible with Twig in Craft.</p>

<p>How can I achieve that?</p>

<templating><array>
Iterate through all entries and count a specific value
# Iterate through all entries and count a specific value

(Asked by: username_0 on 2017-02-20)

I am having entries in a Craft channel-section. Each entry has the field "type" with one category filled. I need to iterate through the entries and count the amount of each category.
Example:
Entry 1, Category: One
Entry 2, Category: One
Entry 3, Category: Two

Produces something like
One: 2, Two: 1

So I know which category is used how often. In any language I would use a key/value set and just increment the amount each time I find the specific category, but that seems to be impossible with Twig in Craft.
How can I achieve that?

**Tags:** templating, array


---

## 1 answers

### Answer by username_1 on 2017-02-20. Score: 3 | Accepted answer

Before we proceed, let me say that whilst the following will work, I personally think this is a poor use of Twig.
It's far better to collate this information in a simple plugin, rather than jumping through such hoops in your templates.
Caveats dispensed with, here you go:
{% set criteria = {
    section: 'exampleSection',
    limit: 20,
    with: ['categoryFieldHandle']
} %}

{% set categories = {} %}
{% set entries = craft.entries(criteria).find() %}

{% for entry in entries %}
    {% set entryCategories = entry.categoryFieldHandle %}
    {% if entryCategories|length %}
        {% for entryCategory in entryCategories %}
            {% set categorySlug = entryCategory.slug %}

            {% if categories[categorySlug] is not defined %}
                {% set categories = categories|merge({
                    (categorySlug): {
                        count: 0,
                        category: entryCategory
                    }
                }) %}
            {% endif %}

            {% set categoryCount = attribute(categories, categorySlug)['count'] + 1 %}

            {% set categories = categories|merge({
                (categorySlug): {
                    count: categoryCount,
                    category: entryCategory
                }
            }) %}
        {% endfor %}
    {% endif %}
{% endfor %}

{% if categories|length %}
    Category Counts
    
        {% for categoryKey, categoryInfo in categories %}
            {{ categoryInfo.category.title }}: {{ categoryInfo.count }}
        {% endfor %}
    
{% endif %}

Note that we're eager loading the categories. Otherwise, we'll end up with N+1 queries.

> **Comments:**
> **username_0**: Thanks a lot! I will look into plugins then and start with this  
> **username_1**: Sounds good. You can translate the above approach to PHP pretty easily.  

---

