Duplicating arrays is a pretty common task for developers. Here’s 3 ways to copy $myArray to $arrayCopy:
Method 1: Reference (shallow copy)
In this example, $arrayCopy becomes another reference to $myArray. Updates to $myArray also update $arrayCopy.
$arrayCopy = $myArray;
Method 2: Loop and copy values (deep copy)
In this method, each item (assuming they are simple types like string, integer, or boolean) is copied to the new array. Changing $myArray will not affect $arrayCopy (unless in the case of, for example, a DateTime object, in which case you should manually duplicate items like that).
$arrayCopy = array();
foreach ($myArray as $key => $item) {
$arrayCopy[$key] = $item;
}
Method 3: A quick deep copy
The effect of this method is the same as the above, but it’s just a neat way of writing it. Its purpose, in my opinion, is fairly self-explanatory.
$arrayCopy = array_merge($myArray, array());
Recent Comments