In PHP, how do I deep copy arrays with examples?

In PHP, deep copying of arrays can be achieved using various methods. A deep copy means that you are not only copying the array itself but also all nested arrays or objects. Here are some methods for deep copying arrays in PHP:

Methods to Deep Copy Arrays in PHP

Using `serialize()` and `unserialize()`

This method converts the array to a string and then back to an array, creating a deep copy.

$array1 = ['a' => 'apple', 'b' => ['c' => 'cherry']]; $array2 = unserialize(serialize($array1));

Using `array_map()` for nested arrays

You can use `array_map()` on the elements of the array to create a deep copy.

function deepCopyArray($array) { return array_map(function ($item) { return is_array($item) ? deepCopyArray($item) : $item; }, $array); } $array1 = ['a' => 'apple', 'b' => ['c' => 'cherry']]; $array2 = deepCopyArray($array1);

Using a loop

You can manually loop through the array to create a deep copy.

function deepCopy($array) { $copy = []; foreach ($array as $key => $value) { $copy[$key] = is_array($value) ? deepCopy($value) : $value; } return $copy; } $array1 = ['a' => 'apple', 'b' => ['c' => 'cherry']]; $array2 = deepCopy($array1);

deep copy arrays PHP deep copy serialization PHP array copy PHP