Demystifying PHP Array Deep Copy: The Secrets Behind Different Methods

WBOY
Release: 2024-05-02 22:09:02
Original
265 people have browsed it

In PHP, the methods to implement array deep copy include: element-by-element copy, using array_map(), PHP built-in functions clone() and array_slice(), and the third-party library DeepCopy. Element-by-element copying involves using a for loop, array_map() uses a callback function, clone() creates a reference, and array_slice() forces a deep copy. The third-party library DeepCopy is dedicated to deep copying and can be used in complex scenarios. In practical applications, it can be used to clone the items in the shopping cart to avoid affecting the original shopping cart.

Demystifying PHP Array Deep Copy: The Secrets Behind Different Methods

Demystifying PHP array deep copy: the secrets behind different methods

In PHP, arrays are a widely used universal variable type. When you need to manipulate an array and its elements, it is necessary to create copies of them to avoid unintended side-effect modifications to the original array. PHP provides several methods to implement deep copy, each with its own advantages and disadvantages.

Element-by-element copy: Using a for loop

The most basic method is to use a for loop to traverse the array and create a copy element-by-element. The code example is as follows:

<?php

$originalArray = [1, 2, ['a', 'b']];

$newArray = [];
for ($i = 0; $i < count($originalArray); $i++) {
    if (is_array($originalArray[$i])) {
        $newArray[$i] = [];
        for ($j = 0; $j < count($originalArray[$i]); $j++) {
            $newArray[$i][$j] = $originalArray[$i][$j];
        }
    } else {
        $newArray[$i] = $originalArray[$i];
    }
}

print_r($originalArray);
print_r($newArray);
?>
Copy after login

Using array_map()

array_map() function provides a more concise way to apply a custom callback function to each element in the array. To do a deep copy, you can set the callback function as an identity function:

<?php

$originalArray = [1, 2, ['a', 'b']];

$newArray = array_map(function($item) {
    return is_array($item) ? array_map(__FUNCTION__, $item) : $item;
}, $originalArray);

print_r($originalArray);
print_r($newArray);
?>
Copy after login

Use PHP built-in functions: clone() and array_slice()

For simple arrays, the clone keyword creates a new array that contains references to the original array elements. However, if the original array contains a nested array, the nested elements are only referenced and not actually copied. The

array_slice function can be used with clone to force a deep copy of a nested array:

<?php

$originalArray = [1, 2, ['a', 'b']];

$newArray = clone $originalArray;
$newArray[2] = array_slice($newArray[2], 0);

print_r($originalArray);
print_r($newArray);
?>
Copy after login

Using an external library: DeepCopy

If you frequently need to do deep copies, you can use a third-party library such as DeepCopy, which is specialized in deep copying objects and arrays.

<?php

useDeepCopy\DeepCopy;

$copier = new DeepCopy();

$originalArray = [1, 2, ['a', 'b']];

$newArray = $copier->copy($originalArray);

print_r($originalArray);
print_r($newArray);
?>
Copy after login

Practical case: Clone the items in the shopping cart

The following example demonstrates how to use deep copy to clone the items in the shopping cart so that the items can be modified without affecting the original shopping. Car:

<?php

class Product {
    public $name;
    public $price;

    public function __construct($name, $price) {
        $this->name = $name;
        $this->price = $price;
    }
}

class Cart {
    private array $products;

    public function addProduct(Product $product) {
        $this->products[] = $product;
    }

    public function getProducts() {
        return $this->products;
    }

    public function cloneProducts() {
        $copier = new DeepCopy();
        return $copier->copy($this->products);
    }
}

$cart = new Cart();
$cart->addProduct(new Product('Apple', 1.5));
$cart->addProduct(new Product('Banana', 2.0));

$clonedProducts = $cart->cloneProducts();

$clonedProducts[0]->price = 1.8;

print_r($cart->getProducts());
print_r($clonedProducts);
?>
Copy after login

The above is the detailed content of Demystifying PHP Array Deep Copy: The Secrets Behind Different Methods. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!