I often see people using array_merge
function in a for
/foreach
/while
loop 😱 like this :
$arraysToMerge = [ [1, 2], [2, 3], [5, 8] ];
$arraysMerged = [];
foreach($arraysToMerge as $array) {
$arraysMerged = array_merge($arraysMerged, $array);
}
It's a very bad practice because it's a performance killer (especially in memory).
Since PHP 5.6, there is a new operator : the spread operator
$arraysToMerge = [ [1, 2], [2, 3], [5,8] ];
$arraysMerged = array_merge([], ...$arraysToMerge);
- No more performance problem
- BONUS : no more
for
/foreach
/while
loop - BONUS : process in one line
Look now at your code base to find code that you can improve 👩💻👨💻!
Thank you for reading, and let's stay in touch !
If you liked this article, please share. You can also find me on Twitter/X for more PHP tips.
Oldest comments (10)
Hi :)
I think you meant in PHP 7.4? wiki.php.net/rfc/spread_operator_f...
Hi,
No, this work in PHP 5.6 : php.net/manual/en/migration56.new-..., "Argument unpacking via ..." section
Oh! Indeed, array_merge is a function so variadic arguments work… Did not think about it . Thx!
Hi! Nice article.
Could you maybe also add some performance stats comparing both approaches?
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...
In this case, you have to do a intermediate process
A fancy way:
So basically different way of using
array_merge
so it stillarray_merge
after all :?Sorry but I don't understand your comment...
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