php array copy key value subarray

PHP Array Duplicate, Copy & Clone To Another Array (9 Methods)

The PHP language offers a number of ways to copy or clone an array to another array with and without reference. PHP array copy or clone is an action to duplicate a PHP array (deep copy and shallow copy). This clone can be done in many ways such as = operator, pointer, ArrayObject class, and user-defined function to copy an array with subarray in PHP.

When working with arrays in PHP, you may need to create a duplicate of an existing array. This is where the array copy comes in. There are several built-in PHP functions to copy arrays in PHP too.

PHP deep copy or clone and shallow copy of an array

A deep copy in PHP is an array clone with a unique reference and dedicated space in memory. A deep copy or duplicate of an array in PHP is a copy of an array that contains all the elements of the original array and any additional elements that are contained within the original array.

A shallow copy is an array clone with shared reference and memory space. A shallow copy of an array in PHP is a copy and clone of an array that only copies the values of the array elements, not the references. This means that if the original array contains objects, the shallow copy will contain references to the same objects.

A deep copy or clone of an array is different from a shallow copy in PHP, which only duplicates the elements of the original array and does not include any additional elements.

1. How to duplicate an array in PHP by = operator

In PHP, all variables except objects are assigned by the copy-on-write mechanism, while things are assigned by reference. This means that for the arrays with scalar values simply by = operand. This method is a deep copy and clone of the array in PHP.

$cars=array('fer'=>'Ferrari','ben'=>'Benz','bmw'=>'BMW');

$cars2=$cars;

var_dump($cars2);

Output

array (size=3)
  'fer' => string 'Ferrari' (length=7)
  'ben' => string 'Benz' (length=4)
  'bmw' => string 'BMW' (length=3)

You need to just assign them to another variable to get a copy of that array. It is the simplest copy, clone, or duplicate of an array in PHP.

2. PHP array duplicate by pointer with reference

In the previous section, you have 2 different arrays with the same keys and values. But if you use a pointer (&) you will have one array with 2 names. This method is a shallow array clone in PHP or a copy of an array with reference.

Let’s see how to make a shallow copy or shallow duplicate of an array in PHP with reference.

$cars=array('fer'=>'Ferrari','ben'=>'Benz','bmw'=>'BMW');

$cars2=&$cars;

var_dump($cars2);

Output

array (size=3)
  'fer' => string 'Ferrari' (length=7)
  'ben' => string 'Benz' (length=4)
  'bmw' => string 'BMW' (length=3)

As the clone is a shallow copy, changing it affects the original because they both point to the same PHP array residing in the same memory space another name of the method is referencing. If you change a value in the array, the other array value will be changed.

$cars=array('fer'=>'Ferrari','ben'=>'Benz','bmw'=>'BMW');

$cars2=&$cars;

$cars['vol']='Volvo';

var_dump($cars2);

Output

array (size=4)
  'fer' => string 'Ferrari' (length=7)
  'ben' => string 'Benz' (length=4)
  'bmw' => string 'BMW' (length=3)
  'vol' => string 'Volvo' (length=5)

All you 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.

3. By ArrayObject class

Another way to clone, copy, or duplicate the array is by using the PHP ArrayObject class. The getArrayCopy() function of the ArrayObject class in PHP is used to create a copy of this ArrayObject. This PHP function returns the copy of the array present in this ArrayObject.

$cars = new ArrayObject(['fer' => 'Ferrari', 'ben' => 'Benz', 'bmw' => 'BMW']);

$cars2 = $cars->getArrayCopy();

var_dump($cars2);

Output

array (size=3)
  'fer' => string 'Ferrari' (length=7)
  'ben' => string 'Benz' (length=4)
  'bmw' => string 'BMW' (length=3)

4. Duplicate an array with PHP serialize and unserialize to another array

PHP Serialize and Unserialize are functions used to convert a PHP value to a string or vice versa. Serialize is used to take a PHP value and convert it into a string that can be stored in a database or sent over a network. Unserialize is used to take a string and convert it back into a PHP value.

Serialize is often used to store objects in a database. It takes an object and converts it into a string, which can then be stored in a database. The Unserialize is used to take the string and convert it back into an object. This is useful for retrieving objects from a database.

Serialize and Unserialize can also be used to store complex data structures in a database. For example, an array can be serialized and stored in a database. When the data is needed, it can be unserialized and the data structure can be used in the application.

$cars = array('fer' => 'Ferrari', 'ben' => 'Benz', 'bmw' => 'BMW');

$cars2 = unserialize(serialize($cars));

var_dump($cars2);

Output

array (size=3)
  'fer' => string 'Ferrari' (length=7)
  'ben' => string 'Benz' (length=4)
  'bmw' => string 'BMW' (length=3)

5. Duplicate the array with the PHP array_replace() function

The PHP function array_replace() replaces and duplicates an array’s values with those from another array or value. The array to be changed, the array containing the replacement values, and an optional third array that will be used to replace additional values are the three parameters it requires.

The array whose values will be changed is the array that has to be replaced. The array that holds the values to replace the original values is known as the array containing replacement values. The third array, which is optional, is used to replace any extra values that the initial array might not have contained.

All of the values in the first array will be replaced by the values in the second array using the array replace() function. The remaining values in the first array will remain intact if the second array has fewer items than the first array.

$cars = array('fer' => 'Ferrari', 'ben' => 'Benz', 'bmw' => 'BMW');

$cars2 = array_replace([],$cars);

var_dump($cars2);

Output

array (size=3)
  'fer' => string 'Ferrari' (length=7)
  'ben' => string 'Benz' (length=4)
  'bmw' => string 'BMW' (length=3)

To copy or clone with this function in PHP, you have to pass an empty array as the first parameter. Then this function replaces the second array elements with the first array.

6. Clone and duplicate the array with PHP array_merge() function

The most basic form of the copy or clone of an array is using the PHP array_merge() function. The PHP array_merge() method is an effective tool for merging two or more arrays into a single array, it means you can duplicate the array with this method.
When you need to aggregate data from various sources into a single array, this function is extremely helpful.

When given two or more arrays as inputs, the array merge() function merges them into a single array.
Every element from the first array is taken by the function and added to the end of the second array.
If the same element appears in both arrays, the second array’s element will replace the first array’s element.

This function works exactly like the array_replace() function.

$cars = array('fer' => 'Ferrari', 'ben' => 'Benz', 'bmw' => 'BMW');

$cars2 = array_merge([],$cars);

var_dump($cars2);

Output

array (size=3)
  'fer' => string 'Ferrari' (length=7)
  'ben' => string 'Benz' (length=4)
  'bmw' => string 'BMW' (length=3)

To copy or clone with this function in PHP, you have to pass an empty array as the first parameter. Then this function adds second array elements to the first array’s ends. It means copying the second array to an empty array.

7. How to clone the multidimensional array in PHP with user-defined function (an array and subarray)

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. Here’s the most robust function to deep-clone an array and subarray in PHP.

function clone_array($arr)
{
    $clone = [];
    foreach ($arr as $k => $v) {
        if (is_array($v)) {
            $clone[$k] = clone_array($v);
        }
        elseif (is_object($v)) {
            $clone[$k] = clone $v;
        }
        else {
            $clone[$k] = $v;
        }
    }
    return $clone;
}

$cars = ['fer' => 'Ferrari', 'ben' => 'Benz', 'bmw' => 'BMW'];

$cars2 = clone_array($cars);

var_dump($cars2);

Output

array (size=3)
  'fer' => string 'Ferrari' (length=7)
  'ben' => string 'Benz' (length=4)
  'bmw' => string 'BMW' (length=3)

8- How to clone an array with PHP array_map() function

The array_map() function is a built-in PHP function to iterate an array. With this PHP function, we can iterate the array and copy and clone the elements to another array but to iterate we have to use a recursive function.

$cars = ['fer' => 'Ferrari', 'ben' => 'Benz', 'bmw' => 'BMW'];

function array_clone($array) {
    return array_map(function($element) {
        return ((is_array($element))
            ? array_clone($element)
            : ((is_object($element))
                ? clone $element
                : $element
            )
        );
    }, $array);
}

$cars2 = array_clone($cars);

var_dump($cars2);

Output

array (size=3)
  'fer' => string 'Ferrari' (length=7)
  'ben' => string 'Benz' (length=4)
  'bmw' => string 'BMW' (length=3)

In this example we use the recursive user define array_clone() function to copy the array to another array by the array_map() function.

9- Copy an array to another array with the array_merge_recursive() built-in PHP function

The PHP array_merge_recursive() function is a powerful tool to combine copy and clone two or more arrays into a single array. This function merges the elements of one or more arrays together so that the values of one are appended to the end of the previous array. It is important to note that this function does not change the original arrays but instead returns a new array.

$cars = array('fer' => 'Ferrari', 'ben' => 'Benz', 'bmw' => 'BMW');

$cars2 = array_merge_recursive([],$cars);

var_dump($cars2);

Output

array (size=3)
  'fer' => string 'Ferrari' (length=7)
  'ben' => string 'Benz' (length=4)
  'bmw' => string 'BMW' (length=3)

When using the array_merge_recursive() function, it is important to note that values from later arrays will overwrite the values of earlier arrays. This means that if two arrays have the same key, the value of the last array will be used. It is also important to note that the order of the arrays is important. If the order of the arrays is reversed, the values from the first array will overwrite the values of the second array.

You may like

Shopping Cart