php array copy key value subarray

PHP Array Copy & Clone (7 Methods)

Used before category names. Blog PHP

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. There are several built-in PHP functions to copy arrays in PHP too.

PHP deep copy and shallow copy of an array

A deep copy is an array clone with a unique reference and dedicated space in memory.

A shallow copy is an array clone with shared reference and memory space.

1. How to clone 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.

$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.

2. By pointer

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.

Let’s see how to make a shallow copy of an 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)

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. 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 or copy 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 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. With serialize and unserialize

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. 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. Copy array with array_replace() function

The PHP function array_replace() replaces 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 with array_merge() function

The PHP array_merge() method is an effective tool for merging two or more arrays into a single array.
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 copy 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)

You may like