Php скопировать значения массива

PHP Array Copy & Clone (8 Methods)

PHP array copy or clone is an action to duplicate a PHP array (deep copy and shallow copy). This clone can be done in many ways such as = operator, pointer, ArrayObject class, and user-defined function to copy an array with subarray in PHP.

When working with arrays in PHP, you may need to create a duplicate of an existing array. This is where the array copy comes in. There are several built-in PHP functions to copy arrays in PHP too.

PHP deep copy and shallow copy of an array

A deep copy is an array clone with a unique reference and dedicated space in memory. A deep copy of an array in PHP is a copy of an array that contains all the elements of the original array and any additional elements that are contained within the original array.

A shallow copy is an array clone with shared reference and memory space. A shallow copy of an array in PHP is a copy of an array that only copies the values of the array elements, not the references. This means that if the original array contains objects, the shallow copy will contain references to the same objects.

Читайте также:  Config inc php установить пароль

A deep copy of an array is different from a shallow copy, which only copies the elements of the original array and does not include any additional elements.

1. How to clone an array in PHP by = operator

In PHP, all variables except objects are assigned by the copy-on-write mechanism, while things are assigned by reference. This means that for the arrays with scalar values simply by = operand. This method is a deep copy.

$cars=array('fer'=>'Ferrari','ben'=>'Benz','bmw'=>'BMW'); $cars2=$cars; var_dump($cars2);
array (size=3) 'fer' => string 'Ferrari' (length=7) 'ben' => string 'Benz' (length=4) 'bmw' => string 'BMW' (length=3)

You need to just assign them to another variable to get a copy of that array.

2. By pointer

In the previous section, you have 2 different arrays with the same keys and values. But if you use a pointer (&) you will have one array with 2 names. This method is a shallow array clone in PHP.

Let’s see how to make a shallow copy of an array in PHP.

$cars=array('fer'=>'Ferrari','ben'=>'Benz','bmw'=>'BMW'); $cars2=&$cars; var_dump($cars2);
array (size=3) 'fer' => string 'Ferrari' (length=7) 'ben' => string 'Benz' (length=4) 'bmw' => string 'BMW' (length=3)

As the clone is a shallow copy, changing it affects the original because they both point to the same array residing in the same memory space. If you change a value in the array, the other array value will be changed.

$cars=array('fer'=>'Ferrari','ben'=>'Benz','bmw'=>'BMW'); $cars2=&$cars; $cars['vol']='Volvo'; var_dump($cars2);
array (size=4) 'fer' => string 'Ferrari' (length=7) 'ben' => string 'Benz' (length=4) 'bmw' => string 'BMW' (length=3) 'vol' => string 'Volvo' (length=5)

All you need is to assign the reference to a new variable. Think of a reference as a pointer to the exact memory location of the original array.

3. By ArrayObject class

Another way to clone or copy the array is by using the PHP ArrayObject class. The getArrayCopy() function of the ArrayObject class in PHP is used to create a copy of this ArrayObject. This function returns the copy of the array present in this ArrayObject.

$cars = new ArrayObject(['fer' => 'Ferrari', 'ben' => 'Benz', 'bmw' => 'BMW']); $cars2 = $cars->getArrayCopy(); var_dump($cars2);
array (size=3) 'fer' => string 'Ferrari' (length=7) 'ben' => string 'Benz' (length=4) 'bmw' => string 'BMW' (length=3)

4. With serialize and unserialize

PHP Serialize and Unserialize are functions used to convert a PHP value to a string or vice versa. Serialize is used to take a PHP value and convert it into a string that can be stored in a database or sent over a network. Unserialize is used to take a string and convert it back into a PHP value.

Serialize is often used to store objects in a database. It takes an object and converts it into a string, which can then be stored in a database. Unserialize is used to take the string and convert it back into an object. This is useful for retrieving objects from a database.

Serialize and Unserialize can also be used to store complex data structures in a database. For example, an array can be serialized and stored in a database. When the data is needed, it can be unserialized and the data structure can be used in the application.

$cars = array('fer' => 'Ferrari', 'ben' => 'Benz', 'bmw' => 'BMW'); $cars2 = unserialize(serialize($cars)); var_dump($cars2);
array (size=3) 'fer' => string 'Ferrari' (length=7) 'ben' => string 'Benz' (length=4) 'bmw' => string 'BMW' (length=3)

5. Copy array with array_replace() function

The PHP function array_replace() replaces an array’s values with those from another array or value. The array to be changed, the array containing the replacement values, and an optional third array that will be used to replace additional values are the three parameters it requires.

The array whose values will be changed is the array that has to be replaced. The array that holds the values to replace the original values is known as the array containing replacement values. The third array, which is optional, is used to replace any extra values that the initial array might not have contained.

All of the values in the first array will be replaced by the values in the second array using the array replace() function. The remaining values in the first array will remain intact if the second array has fewer items than the first array.

$cars = array('fer' => 'Ferrari', 'ben' => 'Benz', 'bmw' => 'BMW'); $cars2 = array_replace([],$cars); var_dump($cars2);
array (size=3) 'fer' => string 'Ferrari' (length=7) 'ben' => string 'Benz' (length=4) 'bmw' => string 'BMW' (length=3)

To copy or clone with this function in PHP, you have to pass an empty array as the first parameter. Then this function replaces the second array elements with the first array.

6. Clone with array_merge() function

The PHP array_merge() method is an effective tool for merging two or more arrays into a single array.
When you need to aggregate data from various sources into a single array, this function is extremely helpful.

When given two or more arrays as inputs, the array merge() function merges them into a single array.
Every element from the first array is taken by the function and added to the end of the second array.
If the same element appears in both arrays, the second array’s element will replace the first array’s element.

This function works exactly like the array_replace() function.

$cars = array('fer' => 'Ferrari', 'ben' => 'Benz', 'bmw' => 'BMW'); $cars2 = array_merge([],$cars); var_dump($cars2);
array (size=3) 'fer' => string 'Ferrari' (length=7) 'ben' => string 'Benz' (length=4) 'bmw' => string 'BMW' (length=3)

To copy or clone with this function in PHP, you have to pass an empty array as the first parameter. Then this function adds second array elements to the first array’s ends. It means copying the second array to an empty array.

7. How to copy the multidimensional array in PHP with user-defined function (an array and subarray)

A multidimensional array takes complexity to the next level. It is challenging in way that it can include many levels of subarrays and varying data types. Here’s the most robust function to deep-clone an array and subarray in PHP.

function clone_array($arr) < $clone = []; foreach ($arr as $k =>$v) < if (is_array($v)) < $clone[$k] = clone_array($v); >elseif (is_object($v)) < $clone[$k] = clone $v; >else < $clone[$k] = $v; >> return $clone; > $cars = ['fer' => 'Ferrari', 'ben' => 'Benz', 'bmw' => 'BMW']; $cars2 = clone_array($cars); var_dump($cars2);
array (size=3) 'fer' => string 'Ferrari' (length=7) 'ben' => string 'Benz' (length=4) 'bmw' => string 'BMW' (length=3)

8- How to copy or clone an array with PHP array_map() function

The array_map() function is a built-in PHP function to iterate an array. With this function, we can iterate the array and copy the elements to another array but to iterate we have to use a recursive function.

$cars = ['fer' => 'Ferrari', 'ben' => 'Benz', 'bmw' => 'BMW']; function array_clone($array) < return array_map(function($element) < return ((is_array($element)) ? array_clone($element) : ((is_object($element)) ? clone $element : $element ) ); >, $array); > $cars2 = array_clone($cars); var_dump($cars2);
array (size=3) 'fer' => string 'Ferrari' (length=7) 'ben' => string 'Benz' (length=4) 'bmw' => string 'BMW' (length=3)

In this example we use the recursive user define array_clone() function to copy the array to another array by the array_map() function.

Источник

ArrayObject::getArrayCopy

Returns a copy of the array. When the ArrayObject refers to an object, an array of the properties of that object will be returned.

Examples

Example #1 ArrayObject::getArrayCopy() example

// Array of available fruits
$fruits = array( «lemons» => 1 , «oranges» => 4 , «bananas» => 5 , «apples» => 10 );

$fruitsArrayObject = new ArrayObject ( $fruits );
$fruitsArrayObject [ ‘pears’ ] = 4 ;

// create a copy of the array
$copy = $fruitsArrayObject -> getArrayCopy ();
print_r ( $copy );

The above example will output:

Array ( [lemons] => 1 [oranges] => 4 [bananas] => 5 [apples] => 10 [pears] => 4 )

User Contributed Notes 5 notes

If you did something like this to make your constructor multidimensional capable you will have some trouble using getArrayCopy to get a plain array straight out of the method:
public function __construct ( $array = array(), $flags = 2 )
// let’s give the objects the right and not the inherited name
$class = get_class ( $this );

foreach( $array as $offset => $value )
$this -> offsetSet ( $offset , is_array ( $value ) ? new $class ( $value ) : $value );

$this -> setFlags ( $flags );
>
?>

That’s the way I solved it:

public function getArray ( $recursion = false )
// just in case the object might be multidimensional
if ( $this === true )
return $this -> getArrayCopy ();

return array_map ( function( $item ) return is_object ( $item ) ? $item -> getArray ( true ) : $item ;
>, $this -> getArrayCopy () );
>
?>

Hope this was useful!

$data = $likeArray -> getArrayCopy ();
?>
will NOT be magically called if you cast to array. Although I’ve expected it.
$nothing = (array) $likeArray ;
?>
Here, $data != $nothing.

«When the ArrayObject refers to an object an array of the public properties of that object will be returned.»

This description does not seem to be right:

class A
public $var = ‘var’ ;
protected $foo = ‘foo’ ;
private $bar = ‘bar’ ;
>

$o = new ArrayObject (new A ());
var_dump ( $o -> getArrayCopy ());

array(3) [«var»]=>
string(3) «var»
[«*foo»]=>
string(3) «foo»
[«Abar»]=>
string(3) «bar»
>
*/
?>

So it does not only include the public properties.

Is there a difference between casting to an array and using this function?

For instance, if we have:
$arrayObject = new ArrayObject([1, 2, 3]);

Is there a difference between these:
$array = (array) $arrayObject;
vs
$array = $arrayObject->getArrayCopy();

If not, is there any scenario where they would produce different results, or do they produce the result in different ways?

When I used print_r ($fruitsArrayObject) instead of print_r ($copy), i.e. ignoring the getArrayCopy() step, I still got the same output. Why?

Источник

Оцените статью