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 )
?>
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?