note 81081 deleted from ref.array by levim

From: Date: Tue, 06 May 2014 22:07:00 +0000
Subject: note 81081 deleted from ref.array by levim
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-199460@lists.php.net to get a copy of this message
Note Submitter: dennis at DONTSPAMME dot born05 dot nl ---- I haven't completely figured out when or why an array gets referenced or copied, but it gave me quite the headache.. So i wrote a function which recursively copies an array while preserving keys and also clones objects if encountered <?php /** * make a recursive copy of an array * * @param array $aSource * @return array copy of source array */ function array_copy ($aSource) { // check if input is really an array if (!is_array($aSource)) { throw new Exception("Input is not an Array"); } // initialize return array $aRetAr = array(); // get array keys $aKeys = array_keys($aSource); // get array values $aVals = array_values($aSource); // loop through array and assign keys+values to new return array for ($x=0;$x<count($aKeys);$x++) { // clone if object if (is_object($aVals[$x])) { $aRetAr[$aKeys[$x]]=clone $aVals[$x]; // recursively add array } elseif (is_array($aVals[$x])) { $aRetAr[$aKeys[$x]]=array_copy ($aVals[$x]); // assign just a plain scalar value } else { $aRetAr[$aKeys[$x]]=$aVals[$x]; } } return $aRetAr; } ?> I hope i can save someone else's aspirine with this ;)

« previous php.notes (#199460) next »