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.

1

1 Answer 1

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
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.