phparraysloopsobjectpass-by-reference

All objects added to an array via looped array_push() calls have property value unintentionally set by final declaration


This is the example code:

//$pieces is an stdClass object which has 4 elements the foreach loops through
$arr = array();
foreach($pieces as $piece)
{
     $piece->value = 1;
     array_push($arr, $piece);

     $piece->value = 3;
     array_push($arr, $piece);
}

The problem with that is it doesn't use the first array_push, just like it wasnt there, in the results I got:

Array
(
    [0] => stdClass Object
        (
             [piece] = 3
        )
    [1] => stdClass Object
        (
             [piece] = 3
        )
    [2] => stdClass Object
        (
             [piece] = 3
        )
    [3] => stdClass Object
        (
             [piece] = 3
        )
)

While there should be additional 4 keys with the [piece] = 1. Am I doing something wrong?


Solution

  • You'll have to clone the $piece object, your code currently saves references to $piece into $arr. This snippet assumes you need actual copies for both $piece variants in your array.

    $arr = array();
    foreach($pieces as $piece)
    {
         $first_clone = clone $piece;
         $first_clone->value = 1;
         array_push($arr, $first_clone);
    
         $second_clone = clone $piece;
         $second_clone->value = 3;
         array_push($arr, $second_clone);
    }