In PHP, how do I copy arrays in vanilla PHP?

In vanilla PHP, you can copy arrays using a few different methods. The most straightforward way is to use the assignment operator. However, it's important to note that this creates a reference, not a copy. To create a true copy of the array, you can use functions like `array_slice()`, `array_merge()`, or the `...` (spread) operator, depending on your needs. Here’s an example:

<?php // Original array $originalArray = ['apple', 'banana', 'cherry']; // Copying the array using assignment (not a true copy) $referenceArray = $originalArray; // Copying the array using array_slice() $copyArray = array_slice($originalArray, 0); // Copying the array using the spread operator (available in PHP 7.4+) $spreadArray = [...$originalArray]; // Modifying the original array $originalArray[] = 'date'; // Displaying the arrays print_r($originalArray); // Outputs: Array ( [0] => apple [1] => banana [2] => cherry [3] => date ) print_r($referenceArray); // Outputs: Array ( [0] => apple [1] => banana [2] => cherry [3] => date ) print_r($copyArray); // Outputs: Array ( [0] => apple [1] => banana [2] => cherry ) print_r($spreadArray); // Outputs: Array ( [0] => apple [1] => banana [2] => cherry ) ?>

PHP array copy vanilla PHP array manipulation PHP programming