3

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']);
}
JakobAttk
  • 113
  • 3
  • 16

1 Answers1

5

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.

KIKO Software
  • 15,283
  • 3
  • 18
  • 33
  • 1
    I found in my version that you don't actually need to merge into an empty array: https://3v4l.org/NmATQ – Matt Nov 11 '20 at 12:05
  • @Matt OK, I'll change that. I simply copied that code from the question. – KIKO Software Nov 11 '20 at 12:06
  • 2
    @Matt I believe`array_merge(...$arraysToMerge)` works only in PHP 7.4+. For older versions you need `array_merge([], ...$arraysToMerge)` otherwise you risk getting a warning if `arraysToMerge` is an empty array or not traversable – JakobAttk Nov 11 '20 at 12:36