Copy Elements of One Array into Another Array in PHP
Last Updated :
03 Jul, 2024
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);
?>
OutputArray
(
[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);
?>;
OutputArray
(
[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);
?>;
OutputArray
(
[0] => 1
[1] => 2
[2] => 3
)
Using the array_merge Function
In this approach we use the array_merge function to merge the source array into an empty array.
PHP
<?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);
?>
OutputArray
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
Using the array_map Function
In this approach we use array_map function which applies a callback to the elements of the given arrays. If we use a function that returns the value itself, it copies the array.
PHP
<?php
$sourceArray = array(1, 2, 3, 4, 5);
$destinationArray = array_map(function($element) {
return $element;
}, $sourceArray);
print_r($destinationArray);
?>
OutputArray
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
Using array_walk()
In PHP, array_walk() applies a callback function to each element of an array, optionally using additional user-defined parameters. To copy elements from one array to another using array_walk(), push each element into the target array within the callback function.
Example: In this example we are following above explained approach.
PHP
<?php
$array1 = [1, 2, 3, 4, 5];
$array2 = [];
array_walk($array1, function($value) use (&$array2) {
$array2[] = $value;
});
print_r($array2);
?>
OutputArray
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
Using array_slice()
This method involves passing the source array to the array_slice function, which will return a copy of the array.
Example: In this example, the copyArray function uses array_slice to copy all elements of the source array starting from the index 0. This approach effectively creates a new array with the same elements as the original array.
PHP
<?php
function copyArray($sourceArray) {
return array_slice($sourceArray, 0);
}
// Example usage
$originalArray = [1, 2, 3, 4, 5];
$copiedArray = copyArray($originalArray);
print_r($copiedArray);
// Verify that the copied array is a separate instance
$originalArray[0] = 99;
print_r($originalArray);
print_r($copiedArray);
?>
OutputArray
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
Array
(
[0] => 99
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
Array
(
[0] => 1
[1] => 2
[2] => 3
...
Using array_filter() Function
In this approach, the array_filter() function is used to filter elements of the source array. By providing a callback function that always returns true, we effectively copy all elements from the source array to a new array.
Example:
PHP
<?php
// Function to copy elements using array_filter
function copy_elements_using_filter($source_array) {
return array_filter($source_array, function($value) {
return true; // Return true for all elements
});
}
// Example usage:
$original_array = array("apple", "banana", "cherry");
$copied_array = copy_elements_using_filter($original_array);
print_r($copied_array);
?>
OutputArray
(
[0] => apple
[1] => banana
[2] => cherry
)
Similar Reads
How to Insert a New Element in an Array in PHP ? In PHP, an array is a type of data structure that allows us to store similar types of data under a single variable. The array is helpful to create a list of elements of similar types, which can be accessed using their index or key.We can insert an element or item in an array using the below function
5 min read
How to Switch the First Element of an Arrays Sub Array in PHP? Given a 2D array where each element is an array itself, your task is to switch the first element of each sub-array with the first element of the last sub-array using PHP.Example:Input: num = [ ['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']];Output: [ ['g', 'b', 'c'], ['d', 'e', 'f'], ['a', 'h', '
2 min read
How to delete an Element From an Array in PHP ? To delete an element from an array means to remove a specific value or item from the array, shifting subsequent elements to the left to fill the gap. This operation adjusts the array's length accordingly, eliminating the specified element.This article discusses some of the most common methods used i
4 min read
How to use array_merge() and array_combine() in PHP ? In this article, we will discuss about how to use array_merge() and array_combine() functions in PHP. Both functions are array based functions used to combine two or more arrays using PHP. We will see each function with syntax and implementation array_merge() FunctionThis function merges the two or
3 min read
Remove First Element from an Array in PHP Given an array, the task is to remove the first element from an array in PHP. Examples:Input: arr = [1, 2, 3, 4, 5, 6, 7]; Output: 2, 3, 4, 5, 6, 7 Input: arr = [3, 4, 5, 6, 7, 1, 2] Output: 4, 5, 6, 7, 1, 2Below are the methods to remove the first element from an array in PHP:Table of ContentUsing
3 min read
Removing Array Element and Re-Indexing in PHP In order to remove an element from an array, we can use unset() function which removes the element from an array, and then use array_values() function which indexes the array numerically automatically. Function Usedunset(): This function unsets a given variable. Syntax:void unset ( mixed $var [, mix
2 min read
What are array_map(), array_reduce() and array_walk() function in PHP ? In this article, we will see array_map(), array_reduce(), and array_walk() functions in PHP. We will see how these functions work along with understanding their basic implementation through the examples. array_map() Function: The array_map() function returns an array containing the results of applyi
3 min read
PHP Merging two or more arrays using array_merge() The array_merge() function in PHP combines two or more arrays into one. It merges the values from the arrays in the order they are passed. If arrays have duplicate string keys, the latter values overwrite earlier ones, while numerical keys are re-indexed sequentially.Syntaxarray array_merge($array1,
2 min read
PHP | array_column() Function The array_column() is an inbuilt function in PHP and is used to return the values from a single column in the input array. Syntax: array array_column($input_array, $column_number, $index_key); Parameters: Out of the three parameters, two are mandatory and one is optional. Let's look at the parameter
3 min read
How to merge the first index of an array with the first index of second array? The task is to merge the first index of an array with the first index of another array. Suppose, an array is array1 = {a, b, c} and another array is array2 = {c, d, e} if we perform the task on these arrays then the output will be result array { [0]=> array(2) { [0]=> string(1) "a" [1]=> st
3 min read