-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 )
1

1 Answer 1

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>";
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.