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

kingshark's avatar

Can anyone explain why this usage of flatMap works?


    public function authorsOfPostComments($posts)
    {
        $commentAuthors = [];
        
        foreach ($posts as $post){
            foreach ($post->comments as $comment){
                foreach ($comment->authors as $author){
                    if (! in_array($author, $commentAuthors)){
                        $commentAuthors[] = $author;
                    }
                }
            }
        }
        
        return $commentAuthors;
        
    }

this function can be simplified to:


    public function authorsOfPostComments($posts)
    {
        return $posts->flatMap->authors->unique();

    }

how does the flatMap of second code work?

0 likes
1 reply
ChristophHarms's avatar
Level 18

As can be seen in the code, flatMap() first applies a callback to each element of the collection and then applies collapse(). collapse() just applies Arr::collapse() to the Collections items. Arr::collapse() flattens the array by one level, meaning it converts an array of arrays to a single array.

Additionally, a feature called higher order messages is used here. This is a feature I haven't made myself perfectly familiar with yet, but as far as I understand it, your second code example without higher order messages would look like this:

public function authorsOfPostComments($posts)
{
    return $posts->flatMap(function ($post) {
        return $post->authors->unique();
    });
}

Looking at this, this only works if you have an authors relation on the post that is a hasManyThrough relation, where the "through" part is comments.

EDIT: The second link in my answer was wrong, I corrected it now.

1 like

Please or to participate in this conversation.