Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jeloqim's avatar

php object reference

Maybe I have a typo or maybe I don't understand how php variable referencing works.

I have an array : $comments = array_fill(0, $numComments, "0"); and I have a comments Collection filled with Comment objects and each comment object might have a children property that contains a collection of comments: $commentsCollection = MyModel::getComments();

I am getting the comments collection fine. When I dd it, it looks good. So I want to fill the array, $comments where the key is the comment's id and the value is the Comment object.

So I wrote this recursive function:

private function fillArrayWithComments(array $commentsArray, $commentsCollection){
    
    foreach($commentsCollection as $comment){
        if ($comment->children){
            $this->fillArrayWithComments($commentsArray, $comment->children);
        }
        $commentsArray[$comment->id] = $comment;
        //dd($commentsArray);
    }
}

and I call it like this $this->fillArrayWithComments($comments, $commentsCollection);

when I uncomment the dd code in the fillArrayWithComments above, then I see that it puts the correct object at the right location. but when I do dd($comments); after the function has run then I get my original array, as if it was never updated. Why is this? what am i doing wrong?

0 likes
3 replies
bobbybouwmann's avatar
Level 88

You need to return the array and assign it to a new value

$myArray = fillArrayWithComments($myArray, $commentsCollection);

private function fillArrayWithComments(array $commentsArray, $commentsCollection) {
    // Do something with the comments

    return $commentsArray;
}
1 like
jeloqim's avatar

Ok, it worked. Why is that the case though?

bobbybouwmann's avatar

You modify something but you don't return it, so next function just picks up the old variable. You can however make this work if you pass the array by reference to the function. However I wouldn't recommend that

Please or to participate in this conversation.