# Total sum within loop

I have simple loop:

``````{% for total in thing %}
{{ total.seatsKids }} {{ total.seatsParents }}
{% endfor %}
``````

This results in a string of numbers eg. `1 3 4`. I want the sum of all numbers. So how do I get `7` at the end? I don't understand how to write math operations within loops.

• Where does the "1" come from? Did you mean "3 4"? Aug 20 '16 at 14:21

To do math in twig, you will need to use the set tag to do assignments, and the + operator to do addition. When doing math inside a for loop, you will need to keep in mind that

loops are scoped in Twig; therefore a variable declared inside a for loop is not accessible outside the loop itself. If you want to access the variable, just declare it before the loop.

It looks as if you have a collection of things that represent seat counts, and you want to loop over them and calculate the totals. So, something like this:

``````{# define and intialize our variables outside the loop #}
{% set kidSeatTotal = 0 %}
{% set parentSeatTotal = 0 %}

{# loop over the seatCounts and add them up #}
{% for seatCount in thing %}
{% set kidSeatTotal = kidSeatTotal + seatCount.seatsKids %}
{% set parentSeatTotal = parentSeatTotal + seatCount.seatsParents %}
{% endfor %}

{# maybe we want the grand total as well #}
{% set grandSeatTotal = kidSeatTotal + parentSeatTotal %}

{# now we can output them: #}
kid seat total: {{ kidSeatTotal }}
parent seat total: {{ parentSeatTotal }}
grand total: {{ grandSeatTotal }}
``````

You could use some twig math, found at the bottom of the page here:

Twig Templating

Not sure without seeing the rest of your code, but you could do something like this:

``````{% set totals = [3,4]%}
{% for total in totals %}
{{ total }}
{% set sum = total + sum ?? 0 %}
{% if loop.last %}{{ sum }}{% endif %}
{% endfor %}
``````

Should output 34 and lastly 7

Or more specifically to your code, roughly (not tested)

``````{% for total in thing %}
{{ total.seatsKids }} {{ total.seatsParents }}
{% set sum = total.seatKids + total.seatsParents + sum ?? 0 %}
{% if loop.last %}{{ sum }}{% endif %}
{% endfor %}
``````

Should output 123456 and lastly 21