DEV Community

Discussion on: Never use array_merge in a loop in PHP

Collapse
 
attkinsonjakob profile image
Jakob Attkinson

This solution is pretty cool, however if you have an array of objects this solution won't work anymore.

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? I can't find a better solution than this...

$accounts = [];
foreach ($users as $user) {
    $accounts = array_merge($accounts, $user['socialMediaAccounts']);
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
klnjmm profile image
Jimmy Klein • Edited

In this case, you have to do a intermediate process

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

$accounts = array_merge([], ...$accounts);
Enter fullscreen mode Exit fullscreen mode
Collapse
 
jfernancordova profile image
José Córdova • Edited

A fancy way:

$accounts = array_map(static function($user){
    return $user['socialMediaAccounts'];
}, $users);

$accounts = array_merge([], ...$accounts);
Enter fullscreen mode Exit fullscreen mode