Open In App

Copy Elements of One Array into Another Array in PHP

Last Updated : 17 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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.

Using Assignment Operator

The simplest way to copy elements from one array to another is by using the assignment operator.

PHP




<?php
  
$arr = [1, 2, 3, 4, 5];
  
$copyArr = $arr;
  
// Display the copied array
print_r($copyArr);
  
?>


Output

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)

Using foreach Loop

You can use a loop, such as foreach to iterate through the source array and copy its elements into the destination array.

PHP




<?php
  
$arr = [1, 2, 3];
$copyArr = [];
  
foreach ($arr as $element) {
    $copyArr[] = $element;
}
  
// Display the copy array
print_r($copyArr);
  
?>


Output

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
)

Using Spread Operator

The spread operator (…) is available in PHP 7.4 and later versions and allows you to unpack the elements of one array into another.

PHP




<?php
  
$arr = [1, 2, 3];
$copyArr = [...$arr];
  
// Display the copy array
print_r($copyArr);
  
?>


Output

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
)


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads