note 63598 deleted from ref.array by levim
| From: | levim@php.net | Date: | Tue, 06 May 2014 22:00:26 +0000 |
| Subject: | note 63598 deleted from ref.array by levim | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-199437@lists.php.net to get a copy of this message | ||
Note Submitter: elkabong at samsalisbury dot co dot uk
----
Hello all! I've just been working on a system to automatically manage virtualhosts on an Apache
box and I needed to duplicate some multidimensional arrays containing references to other
multidimensional array some of which also contained references. These big arrays are defaults which
need to be overwritten on a per-virtualhost basis, so copying references into the virtualhost arrays
was not an option (as the defults would get corrupted).
After hours of banging me head on the wall, this is what I've come up with:
<?PHP # Tested on PHP Version 5.0.4
# Recursively set $copy[$x] to the actual values of $array[$x]
function array_deep_copy (&$array, &$copy) {
if(!is_array($copy)) $copy = array();
foreach($array as $k => $v) {
if(is_array($v)) {
array_deep_copy($v,$copy[$k]);
} else {
$copy[$k] = $v;
}
}
}
# To call it do this:
$my_lovely_reference_free_array = array();
array_deep_copy($my_array_full_of_references, $my_lovely_reference_free_array);
# Now you can modify all of $my_lovely_reference_free_array without
# worrying about $my_array_full_of_references!
?>
NOTE: Don't use this on self-referencing arrays! I haven't tried it yet but I'm
guessing an infinate loop will occur...
I hope someone finds this useful, I'm only a beginner so if there's any fatal flaws or
improvements please let me know!