note 81081 added to ref.array

From: Date: Wed, 13 Feb 2008 15:22:53 +0000
Subject: note 81081 added to ref.array
Groups: php.notes 
Request: Send a blank email to php-notes+get-136117@lists.php.net to get a copy of this message
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 ;) ---- Server IP: 83.137.20.135 Probable Submitter: 83.83.5.143 ---- Manual Page -- http://www.php.net/manual/en/ref.array.php Edit -- https://master.php.net/note/edit/81081 Del: integrated -- https://master.php.net/note/delete/81081/integrated Del: useless -- https://master.php.net/note/delete/81081/useless Del: bad code -- https://master.php.net/note/delete/81081/bad+code Del: spam -- https://master.php.net/note/delete/81081/spam Del: non-english -- https://master.php.net/note/delete/81081/non-english Del: in docs -- https://master.php.net/note/delete/81081/in+docs Del: other reasons-- https://master.php.net/note/delete/81081 Reject -- https://master.php.net/note/reject/81081 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#136117) next »