-1

When I copy PHP array with reference, copy already has references from original

$arr = [1,2,3];
print_r($arr); echo"<br>";    
$x = &$arr[1];
$arr2 = $arr;
print_r($arr); print_r($arr2); echo"<br>";
$x = 8;
print_r($arr); print_r($arr2); echo"<br>";

Result:

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

How can I copy an array, so it has not changed with the original reference?

Array ( [0] => 1 [1] => 2 [2] => 3 ) 
Array ( [0] => 1 [1] => 2 [2] => 3 ) Array ( [0] => 1 [1] => 2 [2] => 3 ) 
Array ( [0] => 1 [1] => 8 [2] => 3 ) Array ( [0] => 1 [1] => 2 [2] => 3 )
Kuznetz
  • 1
  • 2
  • 4
    Possible duplicate of [php copying array elements by value, not by reference](http://stackoverflow.com/questions/1190026/php-copying-array-elements-by-value-not-by-reference) – Muhammad Saqlain Feb 19 '17 at 19:27

1 Answers1

0

If your issue is solved using the duplicate link in your question's first comment (supported by 4 others at the time I'm writing this). Please delete your question so that SO can reduce duplicate questions / needless bloat.

Otherwise, just declare a static copy of the original array for future use.

$arr = [1,2,3];
$copy=$arr;  // preserve the original
print_r($arr); echo"<br>";    
$x = &$arr[1];
$arr2 = $arr;
print_r($arr); print_r($arr2); echo"<br>";
$x = 8;
print_r($arr); print_r($copy); echo"<br>";
mickmackusa
  • 43,625
  • 12
  • 83
  • 136