Search code examples
phparraysarray-merge

How to avoid array_merge in loops when dealing with array of objects


There are a bunch of discussions around 'array_merge(...)' is used in a loop and is a resources greedy construction.

For simple arrays there is an easy solution using the spread operator. E.g.

$arraysToMerge = [ [1, 2], [2, 3], [5,8] ];
$arraysMerged = array_merge([], ...$arraysToMerge);

However, my problem is that I couldn't find a way to avoid it in the following scenario:

Say you have a list of users and each use has multiple social media accounts.

How would you create an array that has all the social media accounts from all the users? The only solution I found is something like this:

$allSocialMediaAccounts= [];
foreach ($users as $user) {
    $allSocialMediaAccounts= array_merge($accounts, $user['socialMediaAccounts']);
}

Solution

  • You can get the $arraysToMerge using the array_column() function on $users like this:

    $arraysToMerge = array_column($users, 'socialMediaAccounts');
    $arraysMerged  = array_merge(...$arraysToMerge);
    

    Matt suggested that you don't need to merge into an empty array, so I adapted the code to his suggestion.