3v4l.org

run code in 300+ PHP versions simultaneously
<?php $json = '[ {"recipient_name":"John D", "phone_number":"123456"}, {"recipient_name":"Doe J", "phone_number":"654321"}, {"recipient_name":"Jon Do", "phone_number":"112233"} ]'; $myLargerArray = json_decode($json, true); $myObjArray = (object)['message_recipients' => 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, clone $myRecipientsObj); var_dump($myObjArray->message_recipients); // The output shows array elements are being overwritten at each loop iteration }
Output for 8.0.0 - 8.0.30, 8.1.0 - 8.1.28, 8.2.0 - 8.2.18, 8.3.0 - 8.3.6
Fatal error: Uncaught Error: Attempt to assign property "recipient_name" on null in /in/UcITu:12 Stack trace: #0 {main} thrown in /in/UcITu on line 12
Process exited with code 255.
Output for 7.1.0 - 7.1.33, 7.2.0 - 7.2.34, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33
Warning: Creating default object from empty value in /in/UcITu on line 12 array(1) { [0]=> object(stdClass)#3 (2) { ["recipient_name"]=> string(6) "John D" ["phone_number"]=> string(6) "123456" } } array(2) { [0]=> object(stdClass)#3 (2) { ["recipient_name"]=> string(6) "John D" ["phone_number"]=> string(6) "123456" } [1]=> object(stdClass)#4 (2) { ["recipient_name"]=> string(5) "Doe J" ["phone_number"]=> string(6) "654321" } } array(3) { [0]=> object(stdClass)#3 (2) { ["recipient_name"]=> string(6) "John D" ["phone_number"]=> string(6) "123456" } [1]=> object(stdClass)#4 (2) { ["recipient_name"]=> string(5) "Doe J" ["phone_number"]=> string(6) "654321" } [2]=> object(stdClass)#5 (2) { ["recipient_name"]=> string(6) "Jon Do" ["phone_number"]=> string(6) "112233" } }

preferences:
204.25 ms | 404 KiB | 225 Q