title: Recursive function inside foreach loop php
body: <pre><code>$parents = array(
      array('id'=&gt;1,'parent_id'=&gt;0,'title'=&gt;'Parent1'),
      array('id'=&gt;2,'parent_id'=&gt;1,'title'=&gt;'Child1'),
      array('id'=&gt;3,'parent_id'=&gt;1,'title'=&gt;'Child2'),
      array('id'=&gt;5,'parent_id'=&gt;3,'title'=&gt;'Child2.1'),
      array('id'=&gt;6,'parent_id'=&gt;5,'title'=&gt;'Child2.1.1'),
      array('id'=&gt;7,'parent_id'=&gt;5,'title'=&gt;'Child2.1.2'),
      array('id'=&gt;8,'parent_id'=&gt;7,'title'=&gt;'Child2.1.2.1'),
      array('id'=&gt;9,'parent_id'=&gt;2,'title'=&gt;'Child1.1'),
      array('id'=&gt;10,'parent_id'=&gt;0,'title'=&gt;'Parent2'),
      array('id'=&gt;11,'parent_id'=&gt;2,'title'=&gt;'Child1.2'),
      array('id'=&gt;12,'parent_id'=&gt;6,'title'=&gt;'Child2.1.1.1'),
  );
  
  function childParentTree($parents,$parentId = 0) {
  
      $str = '';
      foreach($parents as $parent):
          if($parentId == $parent['parent_id']) {
               // Create Label
               $str .= '&lt;li&gt;'.$parentId.$parent['title'].'&lt;/li&gt;';
               // search Child
               $str .= childParentTree($parents,$parent['id']);
          }
      endforeach;
  
      return $str;
  }
  
  echo childParentTree($parents);
  </code></pre>
  
  <p>The above code is ok, but when I dry run the code I am confused by the results. After printing</p>
  
  <pre><code>0 
  1
  2
  9
  </code></pre>
  
  <p>for the variable <code>$parentId</code> it prints 11
  That means the previous parent id, but how</p>
  
  <p>Can someone explain why? Thanks in advance. </p>