0

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?

3
  • Tip: Have you considered using $array[] = $value vs array_push for single items? Commented Feb 14, 2014 at 0:52
  • @Marty Sure, results are the same. Commented Feb 14, 2014 at 1:03
  • Of course, it's just nicer to read, faster to type and even more efficient (on a tiny scale). Commented Feb 14, 2014 at 1:07

2 Answers 2

1

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);
}
Sign up to request clarification or add additional context in comments.

2 Comments

I guess the second clone is not needed?
Depends on your use case. If you need all the objects in $arr to be independent from $pieces you need both clones.
1

Objects are always references. You would need to clone the object before trying to use it as if it were two different things.

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.