Why are variables persisting inside of my for loop? Is anyone able to tell me why variables which I've defined inside of a for loop are persisting and retaining their values on into consecutive iterations? In order to overcome this, I've had to set them back to null each time. I'm relatively new to Craft and Twig but this seems like a bug. Has anyone else experienced this?

    {% for entry in entries %}

      {# I shouldn't have to set these to null for each loop iteration, #}
      {# but they seem to be retaining their values #}

      {% set photo = null %}
      {% set width = null %}
      {% set height = null %}
      {% set orientation = null %}

      {% if entry.photo | length %}
        {% set photo = entry.photo.first() %}
        {% set width = photo.width %}
        {% set height = photo.height %}
        {% set orientation = '' %}

        {% if width &gt; height %}
          {% set orientation = 'landscape' %}
        {% elseif height &gt; width %}
          {% set orientation = 'portrait' %}
        {% elseif width == height %}
          {% set orientation = 'square' %}
        {% endif %}
      {% endif %}

      &lt;article class="entry{% if orientation %} {{ orientation }}{% endif %}"&gt;
        {% if entry.photo | length %}
          &lt;img src="{{ photo.getUrl('small') }}" width="{{ photo.getWidth('small') }}" height="{{ photo.getHeight('small') }}" alt="{{ photo.title }}"&gt;
        {% endif %}
      &lt;/article&gt;

    {% endfor %}
This is totally normal and expected behavior. In fact, it's critical for some looping situations, and pretty standard across programming languages. Wouldn't you expect to find this same behavior in PHP?

Think about situations where previous loops build on each other. Here's an example of a situation where loop values need to be retained...

{% set totalPets = 0 %}

{% for petOwner in craft.entries.section('petOwners').find %}

    {% set totalPets = totalPets + petOwner.numberOwned %}

{% endfor %}

&lt;p&gt;This group of people owns {{ totalPets }} pets total.&lt;/p&gt;


Ultimately, this is a simple scope issue. Generally speaking, for loops don't exist in their own scope... they are a part of the scope created by the parent script.

If you want to ensure that your logic takes place in a separate scope, take a look into Twig macros... A macro would probably be very helpful in your situation.