0

This is the code for an object:

$a = new stdClass();
$a->value = 'key';
$array[] = $a;
$array[] = $a;
$a->value = 'key2';
$array[] = $a;
print_r($array);

and this is the code for an array

$a = array("value" => "key");
$array[] = $a;
$array[] = $a;
$a['value'] = 'key2';
$array[] = $a;
print_r($array);

output for object:

Array
(
    [0] => stdClass Object
        (
            [value] => key2
        )

    [1] => stdClass Object
        (
            [value] => key2
        )

    [2] => stdClass Object
        (
            [value] => key2
        )

)

output for array:

Array
(
    [0] => Array
        (
            [value] => key
        )

    [1] => Array
        (
            [value] => key
        )

    [2] => Array
        (
            [value] => key2
        )

)

When $a is an Object, it updates the value already in $array to key2 but when $ais an array it only updates the last value. How can I get the object to behave like the array and only update the last value?

Thank you.

user2029890
  • 2,493
  • 6
  • 34
  • 65
  • 1
    possible duplicate of [How do I create a copy of an object in PHP?](http://stackoverflow.com/questions/185934/how-do-i-create-a-copy-of-an-object-in-php) – kamal pal Aug 03 '15 at 16:28

1 Answers1

2

PHP objects are automatically passed by reference, so if you update the last one it will update everything. So just use clone, to clone your object, e.g.

$array[] = clone $a;
         //^^^^^ See here
Rizier123
  • 58,877
  • 16
  • 101
  • 156