title: How to check for circular references in PHP when recursively parsing an associative array?
body: <p>I created this array with a circular reference:</p>
  
  <pre><code>$arr = array(1 =&gt; 'one', 2 =&gt; 'two');
  $arr[3] = &amp;$arr;
  </code></pre>
  
  <p>I have a function that recursively prints out the values in an array, but I really couldn't solve the problem of creating a circular reference check. How can you do that?</p>
  
  <p>The current function I have for printing the array is copied below. I haven't included the various attempts I made at doing the circular reference check. They mainly revolved around a strategy of maintaining a <code>$seen</code> array of items that have already been printed <em>for each branch of recursion</em>. This is because I still want to allow the printing of duplicate values, just not printing of a value if it is a parent of the current array being parsed.</p>
  
  <p>The problems I had were figuring out how to add references rather than array copies to this <code>$seen</code> variable. But I'd be happy to use another strategy all together if it worked.</p>
  
  <pre><code>function HTMLStringify($arr)
  {
  
      if(is_array($arr)){
          $html = '&lt;ul&gt;';
          foreach ($arr as $key =&gt; $value) {
  
              $html .= '&lt;li&gt;' . $key;
  
              if(is_array($value)){
  
                  //Conspicuously missing is a circular reference check,
                  //causing infinite recursion. After a few failed attempts
                  //at checking for this (e.g. discovering that array_push doesn't take references)
                  //I have left it for further study.
                  //(After all, Javascript's JSON.stringify() doesn't check for circular references)
                  //TODO: Check for circular references
  
                  $html .= HTMLStringify($value, $seen);
              }
              elseif(is_numeric($value) || is_string($value) || is_null($value))
              {
                  $html .= ' = ' . $value;
              }
              else
              {
                  $html .= ' [couldn\'t parse ' . gettype($value) . ']';
              }
  
              $html .= '&lt;/li&gt;';
  
          }
          $html .= '&lt;/ul&gt;';
          return $html;
      }
      else
      {
          return null;
      }
  }
  </code></pre>