Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>(I just posted this as an answer to the <a href="https://stackoverflow.com/questions/9105816/is-there-a-way-to-detect-circular-arrays-in-pure-php">Is there a way to detect circular arrays in pure PHP?</a> question that @Cheery mentioned, but I may be updating that answer depending on that asker's needs.)</p> <p>The isRecursiveArray(array) method below detects circular/recursive arrays. It keeps track of which arrays have been visited by temporarily adding an element containing a known object reference to the end of the array. </p> <pre><code>function removeLastElementIfSame(array &amp; $array, $reference) { if(end($array) === $reference) { unset($array[key($array)]); } } function isRecursiveArrayIteration(array &amp; $array, $reference) { $last_element = end($array); if($reference === $last_element) { return true; } $array[] = $reference; foreach($array as &amp;$element) { if(is_array($element)) { if(isRecursiveArrayIteration($element, $reference)) { removeLastElementIfSame($array, $reference); return true; } } } removeLastElementIfSame($array, $reference); return false; } function isRecursiveArray(array $array) { $some_reference = new stdclass(); return isRecursiveArrayIteration($array, $some_reference); } $array = array('a','b','c'); var_dump(isRecursiveArray($array)); print_r($array); $array = array('a','b','c'); $array[] = $array; var_dump(isRecursiveArray($array)); print_r($array); $array = array('a','b','c'); $array[] = &amp;$array; var_dump(isRecursiveArray($array)); print_r($array); $array = array('a','b','c'); $array[] = &amp;$array; $array = array($array); var_dump(isRecursiveArray($array)); print_r($array); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload