Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I assign an array just by making it equal to another array?

Tags:

arrays

php

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?

like image 780
Roman Avatar asked Jun 16 '10 14:06

Roman


3 Answers

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.

like image 109
Felix Kling Avatar answered Sep 29 '22 18:09

Felix Kling


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);
like image 42
Matteo Riva Avatar answered Sep 29 '22 20:09

Matteo Riva


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
                )

        )

)
*/
like image 32
meouw Avatar answered Sep 29 '22 19:09

meouw