PHP - Ds Map::copy() Function
The PHPDs\Map::copy()function is used to create a shallow copy of a Ds\Map object, and the function returns the same the shallow copy in the result.
A shallow copy of a collection (or map) is a copy where the properties share the same references as those of the source object from which the copy was made.
Syntax
Following is the syntax of the PHP Ds\Map::copy() function −
public Ds\Map::copy(): Ds\Map
Parameters
This function does not accept any parameter.
Return value
This function returns a shallow copy of a map.
Example 1
The following is the basic example of the PHP Ds\Map::copy() function −
<?php $map = new \Ds\Map([1, 2, 3]); echo "The map elements are: \n"; print_r($map); echo "\nThe shallow copy of a map: \n"; #using the copy() function print_r($map->copy()); ?>
Output
The above program produces the following output −
The map elements are:
Ds\Map Object
(
[0] => Ds\Pair Object
(
[key] => 0
[value] => 1
)
[1] => Ds\Pair Object
(
[key] => 1
[value] => 2
)
[2] => Ds\Pair Object
(
[key] => 2
[value] => 3
)
)
The shallow copy of a map:
Ds\Map Object
(
[0] => Ds\Pair Object
(
[key] => 0
[value] => 1
)
[1] => Ds\Pair Object
(
[key] => 1
[value] => 2
)
[2] => Ds\Pair Object
(
[key] => 2
[value] => 3
)
)
Example 2
Following is another example of the PHP Ds\Map::copy() function. We use this function to retrieve a shallow copy of this map (["Tutorials", "Point", "India"]) −
<?php
$map = new \Ds\Map(["Tutorials", "Point", "India"]);
echo "The map elements are: \n";
print_r($map);
print_r("The shallow copy of a map: \n");
#using copy() function
print_r($map->copy());
?>
Output
After executing the above program, it will display the following output −
The map elements are:
Ds\Map Object
(
[0] => Ds\Pair Object
(
[key] => 0
[value] => Tutorials
)
[1] => Ds\Pair Object
(
[key] => 1
[value] => Point
)
[2] => Ds\Pair Object
(
[key] => 2
[value] => India
)
)
The shallow copy of a map:
Ds\Map Object
(
[0] => Ds\Pair Object
(
[key] => 0
[value] => Tutorials
)
[1] => Ds\Pair Object
(
[key] => 1
[value] => Point
)
[2] => Ds\Pair Object
(
[key] => 2
[value] => India
)
)
Example 3
In the example below, we use the copy() function to create a shallow copy of this map (['a', 'b']) −
<?php
$map = new \Ds\Map(['a', 'b']);
echo "The map elements are: \n";
foreach($map as $key=>$value){
echo "[".$key."] = ".$value."\n";
}
print_r("The shallow copy of a map: \n");
#using copy() function
$shallow_cpy = $map->copy();
foreach($shallow_cpy as $key=>$value){
echo "[".$key."] = ".$value."\n";
}
?>
Output
Once the above program is executed, it will display the following output −
The map elements are: [0] = a [1] = b The shallow copy of a map: [0] = a [1] = b