Hi a good day to everyone. I am new to PHP and here I am trying to push multiple objects ($viewership_prj) to a single array ($viewership_prj_arr).
The first time I wrote the following. The resulting array was not correct.
Basically whenever a new object is pushed into the array, all existing objects in that array are overwritten with the properties of that newly pushed object.
$viewership_prj_arr = array();
$viewership_prj = (object) array();
foreach($projects as $prj)
{
/*...*/
$viewership_prj->title = $prj['project_title'];
$viewership_prj_arr[] = $viewership_prj;
// $viewership_prj_arr[] is [title1] after first loop
// [title2, title2] after second loop
// [title3, title3, title3] after third loop
// ...
}
Then I changed to this and it worked. I declared a new object inside each loop.
$viewership_prj_arr = array();
foreach($projects as $prj)
{
/*...*/
$viewership_prj = (object) array();
$viewership_prj->title = $prj['project_title'];
$viewership_prj_arr[] = $viewership_prj;
// $viewership_prj_arr[] is [title1] after first loop
// [title1, title2] after second loop
// [title1, title2, title3] after third loop
// ...
}
I was very confused.
The only reason I could think of is that when the object is pushed into the array, it was passed by reference and not by value. I tried looking up the manual https://www.php.net/manual/en/language.oop5.references.php#:~:text=Objects%20and%20references%20%C2%B6,passed%20by%20references%20by%20default%22.&text=A%20PHP%20reference%20is%20an,the%20object%20itself%20as%20value. but it is not making much sense to me.
Could someone help me clarify this? Much thanks in advance.