DEV Community

Never use array_merge in a loop in PHP

Jimmy Klein on July 08, 2019

I often see people using array_merge function in a for/foreach/while loop 😱 like this : $arraysToMerge = [ [1, 2], [2, 3], [5, 8] ]; $arraysMer...
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
Collapse
 
nguyenhai97ict profile image
Nguyễn Đăng Hải

So basically different way of using array_merge so it still array_merge after all :?

Collapse
 
klnjmm profile image
Jimmy Klein

Sorry but I don't understand your comment...

Collapse
 
chris_daniel profile image
Christopher Daniel • Edited

I think if we pass more than two arrays as arguments, it will call k way merge. It is faster than array_merge in loop

Collapse
 
einenlum profile image
Yann Rabiller

Hi :)

I think you meant in PHP 7.4? wiki.php.net/rfc/spread_operator_f...

Collapse
 
klnjmm profile image
Jimmy Klein

Hi,

No, this work in PHP 5.6 : php.net/manual/en/migration56.new-..., "Argument unpacking via ..." section

Collapse
 
einenlum profile image
Yann Rabiller

Oh! Indeed, array_merge is a function so variadic arguments work… Did not think about it . Thx!

Collapse
 
ohvitorino profile image
Bruno Vitorino

Hi! Nice article.
Could you maybe also add some performance stats comparing both approaches?