How to use the array_merge Function In PHP
In this approach we use the array_merge function to merge the source array into an empty array.
<?php
function copyArray($sourceArray) {
// Use array_merge to merge the source array into an empty array
$copiedArray = array_merge([], $sourceArray);
return $copiedArray;
}
$sourceArray = [1, 2, 3, 4, 5];
$copiedArray = copyArray($sourceArray);
// Print the copied array
print_r($copiedArray);
?>
Output
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 )
Copy Elements of One Array into Another Array in PHP
Copying elements from one array to another is a common operation in PHP. Copy elements operation is used to create a duplicate, merge arrays, or extract specific elements. In this article, we will explore various approaches to copying elements from one array into another in PHP.
Table of Content
- Using Assignment Operator
- Using foreach Loop
- Using Spread Operator
- Using the array_merge Function