I have an array $x with nonzero number of elements. I want to create another array ($y) which is equal to $x. Then I want to make some manipulations with $y without causing any changes to $x. Can I create $y in this way:
$y = $x;
In other words, if I modify $y created in the above shown way, will I change value of $x?
Lets give it a try:
$a = array(0,1,2);
$b = $a;
$b[0] = 5;
print_r($a);
print_r($b);
gives
Array
(
    [0] => 0
    [1] => 1
    [2] => 2
)
Array
(
    [0] => 5
    [1] => 1
    [2] => 2
)
And the documentation says:
Array assignment always involves value copying. Use the reference operator to copy an array by reference.
No, a copy won't change the original.
It would change it if you used a reference to the original array:
$a = array(1,2,3,4,5);
$b = &$a;
$b[2] = 'AAA';
print_r($a);
                        Arrays are copied by value. There is a gotcha tho. If an element is a reference, the reference is copied but refers to the same object.
<?php
class testClass {
    public $p;
    public function __construct( $p ) {
        $this->p = $p;
    }
}
// create an array of references
$x = array(
    new testClass( 1 ),
    new testClass( 2 )
);
//make a copy
$y = $x;
print_r( array( $x, $y ) );
/*
both arrays are the same as expected
Array
(
    [0] => Array
        (
            [0] => testClass Object
                (
                    [p] => 1
                )
            [1] => testClass Object
                (
                    [p] => 2
                )
        )
    [1] => Array
        (
            [0] => testClass Object
                (
                    [p] => 1
                )
            [1] => testClass Object
                (
                    [p] => 2
                )
        )
)
*/
// change one array
$x[0]->p = 3;
print_r( array( $x, $y ) );
/*
the arrays are still the same! Gotcha
Array
(
    [0] => Array
        (
            [0] => testClass Object
                (
                    [p] => 3
                )
            [1] => testClass Object
                (
                    [p] => 2
                )
        )
    [1] => Array
        (
            [0] => testClass Object
                (
                    [p] => 3
                )
            [1] => testClass Object
                (
                    [p] => 2
                )
        )
)
*/
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With