Skip to content

Instantly share code, notes, and snippets.

@boekkooi
Created November 28, 2014 09:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save boekkooi/f83cc79303e936384ea2 to your computer and use it in GitHub Desktop.
Save boekkooi/f83cc79303e936384ea2 to your computer and use it in GitHub Desktop.
Deep copy Array
<?php
function arrayCopy(array $array)
{
$hashList = array();
$iterator = new \RecursiveIteratorIterator(
new \RecursiveArrayIterator($array),
\RecursiveIteratorIterator::SELF_FIRST
);
$iterator->rewind();
$prevDepth = 0;
$current = array();
$parents = array(&$current);
foreach ($iterator as $k => $v) {
if ($iterator->getDepth() < $prevDepth) {
for ($i = ($prevDepth - $iterator->getDepth()); $i > 0; $i--) {
array_pop($parents);
}
$current = &$parents[count($parents)-1];
}
if (is_array($v)) {
$current[$k] = array();
array_push($parents, $current[$k]);
$current =& $current[$k];
} elseif (is_object($v)) {
if (!isset($hashList[spl_object_hash($v)])) {
$hashList[spl_object_hash($v)] = clone $v;
}
$current[$k] = $hashList[spl_object_hash($v)];
} else {
$current[$k] = $v;
}
$prevDepth = $iterator->getDepth();
}
$rtn = $parents[0];
unset($current, $parents, $hashList);
return $rtn;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment