Search code examples
phparraysloopsmultidimensional-arrayarray-push

PHP array_push() is overwriting existing array elements


I'm trying to push objects into an array to end up with an object array like this:

[
    {"recipient_name":"John D", "phone_number":"123456"},
    {"recipient_name":"Doe J", "phone_number":"654321"},
    {"recipient_name":"Jon Do", "phone_number":"112233"},
]

So I'm looping over a larger array to acquire the names and phone numbers and pushing them as an object to an array like this:

$myLargerArray = pg_fetch_all($messageQuery); // This is my larger array

$size = count($myLargerArray);
for( $j = 0; $j < $size; $j++ ) {
    $myRecipientsObj->recipient_name = $myLargerArray[$j]['recipient_name'];
    $myRecipientsObj->phone_number = $myLargerArray[$j]['phone_number'];

    var_dump($myRecipientsObj); // This outputs the correct data added from [$j]

    array_push($myObjArray->message_recipients, $myRecipientsObj);

    var_dump($myObjArray->message_recipients); // The output shows array elements are being overwritten at each loop iteration
}

This is an example of how the last var_dump($myObjArray->message_recipients) looks like:

array(1) {
  [0]=>
  object(stdClass)#2 (2) {
    ["recipient_name"]=>
    string(12) "First Person"
    ["phone_number"]=>
    string(9) "112233445"
  }
}
array(2) {
  [0]=>
  object(stdClass)#2 (2) {
    ["recipient_name"]=>
    string(13) "Second Person"
    ["phone_number"]=>
    string(9) "123456789"
  }
  [1]=>
  object(stdClass)#2 (2) {
    ["recipient_name"]=>
    string(12) "Second Person"
    ["phone_number"]=>
    string(9) "123456789"
  }
}
array(3) {
  [0]=>
  object(stdClass)#2 (2) {
    ["recipient_name"]=>
    string(16) "Third Person"
    ["phone_number"]=>
    string(9) "012345678"
  }
  [1]=>
  object(stdClass)#2 (2) {
    ["recipient_name"]=>
    string(16) "Third Person"
    ["phone_number"]=>
    string(9) "012345678"
  }
  [2]=>
  object(stdClass)#2 (2) {
    ["recipient_name"]=>
    string(16) "Third Person"
    ["phone_number"]=>
    string(9) "012345678"
  }
}
array(4) {
  ... // it just overwriting the data with duplicates
}

What am I doing wrong to cause this and how can I get around it?


Solution

  • It's because when you use:

    array_push($myObjArray->message_recipients, $myRecipientsObj);
    

    you are pushing a reference to the object into the array, and when you then change the object in subsequent passes through the loop, you effectively change the contents of each element of the array. To work around this, you need to push a copy of the object into the array instead:

    array_push($myObjArray->message_recipients, clone $myRecipientsObj);
    

    Demo on 3v4l.org