Copying Arrays (Part 1)

by Sep 30, 2015

When you copy variable content, you may just copy the "reference" (memory address), not the content. Take a look at this example:

$a = 1..10
$b = $a
$b[0] = 'changed'
$b[0]
$a[0] 

Although you changed $b, there was a change in $a as well. Both variables reference the same memory location, so both have identical content.

To create a completely new copy of an array, you need to clone it first:

$a = 1..10
$b = $a.Clone()
$b[0] = 'changed'
$b[0]
$a[0]

Twitter This Tip! ReTweet this Tip!