semi-dirty PHP trick?
Aug. 21st, 2006 12:20 amHow ugly is this approach to making a copy of an array that moves only values, not references?
I feel a little dirty... assuming I'm not too worried about efficiency, should I?
$copy_of_array = unserialize(serialize($multidimensional_array));I feel a little dirty... assuming I'm not too worried about efficiency, should I?
no subject
Date: 2006-08-21 04:34 am (UTC)Even Perl sound sane compared to PHP.
(sorry I don't have a real answer)
no subject
Date: 2006-08-21 05:19 am (UTC)$a2 =& $a1
is not the same as $a1 =& $a2;
The first, you make a copy. $a2 is a brand new variable in the table.
The second, $a2 is a reference to the $a1 symbol.
What you're doing, is the same thing as $a2 = $a1. Serialize just makes a textual representation of a variable. when you unserialize a variable, you get an identical copy, just like doing $a2 = $a1.
no subject
Date: 2006-08-21 12:11 pm (UTC)$a2 = $a1? From my ActionScript days, I've come to expect anything past the first layer to be references to the original arrays, i.e. if $a1 is{$a11,$a12,$a13}with $a11,$a12,$a13 being composite anything, then $a2 is{$a11,$a12,$a13}(changing $a2[2][2] changes $a1[2][2] as well) whereas I want $a2 to contain copies of them, totally freed of any references to any content of $a1.no subject
Date: 2006-08-21 01:00 pm (UTC)$a1[0] = 'hello world';
$a2 = $a1;
$a2[0] = 'foo bar';
echo $a1[0].':'.$a2[0]; // hello world:foo bar
$a2 =& $a1;
$a2[0] = 'foo bar';
echo $a1[0].':'.$a2[0]; // foo bar:foo bar
the = operator means assignment. =& operator means reference.
ecmascript (which is what actionscript/javascript are dervitives of), can be wierd when it comes to references.
var i;
var x;
i = x; // i & x are two seperate variables.
var i;
i = some.global.scope.object; // i is a reference of that object
efficiency
Date: 2006-09-18 01:23 am (UTC)riiiiiiight...
b
Re: efficiency
Date: 2006-09-18 01:49 am (UTC)I eventually found out that PHP 4 has easy cloning behaviour, but PHP 5 acts like ECMAScript, with its "composite types are always piles of references" thing. Ick. Maybe I should learn more C and write webpages in it or something.