Clone & Deep Copy Arrays in PHP | References, Multidimensional

Summary:

There are several built-in php functions to copy arrays in PHP. array_merge, array_map and assigning a variable name. PHP doesn't have pointers so you can assign a new variable without concern about modifying the original.

How to Clone a Deep Copy Array in PHP

Define your original array in PHP as a variable

Create a custom PHP function called cloneArray with a single parameter for array

Inside the cloneArray function instantiate a new empty array.

Create a foreach loop inside of the custom function to iterate the passed array

Run an if statement in the loop to determine if the element is an array

Call the cloneArray function recursively when the element is an array

Assign a new value to the cloned array variable.

Return the cloned array from the custom function.

Pass in your array to deep clone to the custom cloneArray function to start the process.

function cloneArray(array $arr) {
    $clone = [];
    foreach($arr as $k => $v) {
        if(is_array($v)) $clone[$k] = clone_array($v); //If a subarray
        else if(is_object($v)) $clone[$k] = clone $v; //If an object
        else $clone[$k] = $v; //Other primitive types.
    }
    return $clone;
}

Problem understanding it? Stick to the article until the end to learn about this example and much more about array cloning in PHP.

Introduction

There are many ways to copy an array in PHP. However, there are two important terminologies to understand before jumping into the examples. These terminologies are deep copy and shallow copy.

Let’s understand these and then move on to the practical stuff.

Deep Copy

A deep copy is an array clone with a unique reference and dedicated space in memory. Let’s assume array B is a copy of array A. Just because it is a deep copy, thus changing array B doesn’t affect array A.

copy array in php

Shallow Copy

A shallow copy is an array clone with shared reference and memory space. Let’s assume array B is a copy of array A. Just because it is a shallow copy with shared reference and memory, thus changing array B affects array A.

copy array in php

How to copy array in PHP – Assign a copy.

PHP makes a deep copy of an array using the assignment operator. It is just as simple as assigning one variable to another. Here’s how.

<?php
 
$programming_languages = ['PHP', 'Python', 'Javascript'];
 
$programming_languages_clone = $programming_languages;
 
$programming_languages_clone[] = 'Java';
 
//$programming_languages = [PHP, Python, Javascript]
//$programming_languages_clone = [PHP, Python, Javascript, Java]
 
?>

Adding ‘Java’ to the cloned array doesn’t affect the original array. 

How to copy array in PHP – Using array_merge

PHP array_merge is also helpful in creating a deep copy of an array. Let’s revisit the above example.

<?php
 
$programming_languages = ['PHP', 'Python', 'Javascript'];
 
$programming_languages_clone = array_merge([],$programming_languages);
 
$programming_languages_clone[] = 'Java';
 
//$programming_languages = [PHP, Python, Javascript]
//$programming_languages_clone = [PHP, Python, Javascript, Java]
 
?>

The array_merge fuses an empty array with the programming_languages array and returns a new array, a deep copy.

How to copy array in PHP – Assign a reference

Let’s see how to make a shallow copy of an array in PHP. As seen already, a shallow copy shares the reference and memory space. So, all we need is to assign the reference to a new variable. Think of a reference as a pointer to the exact memory location of the original array.

<?php
 
$programming_languages = ['PHP', 'Python', 'Javascript'];
 
$programming_languages_clone = &$programming_languages;
 
$programming_languages_clone[] = 'Java';
 
//$programming_languages = [PHP, Python, Javascript, Java]
//$programming_languages_clone = [PHP, Python, Javascript, Java]
 
?>

The & in PHP is for assigning a reference than a copy. As the clone is a shallow copy, changing it affects the original because they both point to the same array residing in the same memory space.

How to copy array of objects in PHP – Using array_map

Objects are always passed by reference. So contrary to the first example for array copy, assigning one object to another is always by reference. A way out is using the clone keyword.

$employee_1 = new Employee('1', 'Allen', 60000, '29');
$employee_2 = clone $employee_1;

Cloning an array of objects is complicated because the objects always share references.

array of objects

The array is a deep copy, but the object is still a shallow copy. The following example uses the array_map function to make a deep clone of an array of objects.

$employees_arr =
[
    new Employee('5', 'Brian', 90000, '25'),
    new Employee('1', 'Allen', 60000, '29'),
    new Employee('2', 'Kylie', 50000, '27'),
    new Employee('3', 'Jeane', 80000, '35'),
    new Employee('4', 'Franklin', 75000, '30'),
];
 
 
$employees_arr_clone = array_map(function($obj) {return clone $obj;},$employees_arr);

The array_map function returns an array of deeply cloned objects. 

How to copy multidimensional array in PHP

A multidimensional array takes complexity to the next level. It is challenging in a way that it can include many levels of subarrays and varying data types. We need a robust code, one ring to rule them all. So, a recursive function is a way to go.

function clone_array($arr) {
    $clone = array();
    foreach($arr as $k => $v) {
        if(is_array($v)) $clone[$k] = clone_array($v); //If a subarray
        else if(is_object($v)) $clone[$k] = clone $v; //If an object
        else $clone[$k] = $v; //Other primitive types.
    }
    return $clone;
}

This function is robust enough to handle all kinds of arrays. Here’s how it works.

  • It traverses the array and checks the type of elements.
  • If the element is an array, it recursively calls the function to repeat the logic.
  • If the element is an object, it makes a clone, a deep copy.
  • Else, for the primitive type, it just assigns it to the key.

That’s all about it. We have pretty much seen all about array cloning in PHP.

Conclusion

The article explores how to copy array in PHP. It starts with differentiating deep copy and shallow copy. Following that section, it includes several ways to make an array clone. Following this, we see how to make a clone of an array of objects. Finally, we create one ring to rule them all, and that’s the last function we have just seen.

Hopefully, you’ve enjoyed the article. Stay tuned for more articles like these at FuelingPHP.

Want to learn more about PHP?

We have many fun articles related to PHP. You can explore these to learn more about PHP.


Article Categories

Article Tags

© 2022 Confident.Systems