title: foreach loop for creating a HTML markup from a PHP array
body: <p>Imagine you have an array of HTML elements (in their appearance order) as</p>
  
  <pre><code>$array = array(
    1=&gt;array( 'level' =&gt; 1, 'element' =&gt; '&lt;div class="parent"&gt;'),
    2=&gt;array( 'level' =&gt; 2, 'element' =&gt; '&lt;div class="child"&gt;'),
    3=&gt;array( 'level' =&gt; 3, 'element' =&gt; '&lt;span class="child2"&gt;'),
    4=&gt;array( 'level' =&gt; 2, 'element' =&gt; '&lt;div class="child"&gt;'),
    5=&gt;array( 'level' =&gt; 2, 'element' =&gt; '&lt;div class="child"&gt;'),
    6=&gt;array( 'level' =&gt; 3, 'element' =&gt; '&lt;span class="child2"&gt;'),
    7=&gt;array( 'level' =&gt; 4, 'element' =&gt; '&lt;span class="child3"&gt;'),
  );
  </code></pre>
  
  <p>How do you plan a <code>foreach</code> loop to find the places of the closing HTML tags to output a string as</p>
  
  <pre><code>&lt;div class="parent"&gt;
      &lt;div class="child"&gt;
          &lt;span class="child2"&gt;
          &lt;span&gt;
      &lt;/div&gt;
      &lt;div class="child"&gt;
      &lt;/div&gt;
      &lt;div class="child"&gt;
          &lt;span class="child2"&gt;
              &lt;span class="child3"&gt;
              &lt;/span&gt;
          &lt;/span&gt;
      &lt;/div&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>My attempt was something like</p>
  
  <pre><code>foreach($array as $e){
  
  echo $e['element'];
  
  $level = $e['level'];
      if($level&lt;=$previous_level) {
      echo $closing; 
      $closing = '';
      }
  $closing.= '&lt;/'. $element . '&gt;'; // which comes from parsed $e['element'];
  
  $previous_level = $level;
  }
  </code></pre>