DEV Community

Discussion on: Never use array_merge in a loop

Collapse
 
moopet profile image
Ben Sinclair

I try to avoid anything like this in PHP because I always have to look up what the difference is between array_merge and the + operator, and what order to use parameters in and which bits are going to be OO today and which bits aren't. It's just horrible.

I didn't even know there was a spread operator in PHP!

Collapse
 
moopet profile image
Ben Sinclair

Ah, it looks like it's been in PHP since 5.6 as an argument unpacker but only been able to unpack general arrays since 7.4.

Collapse
 
chemaclass profile image
Jose Maria Valera Reales

Well, you can use it for versions <7.4 as:

$merged = array_merge([], ...array_values($lists));
Enter fullscreen mode Exit fullscreen mode

Check it out: sandbox.onlinephpfunctions.com/cod...

And from 7.4, array_merge accept no arguments, therefore we can use it without the empty array as first arg:

$merged = array_merge(...array_values($lists));
Enter fullscreen mode Exit fullscreen mode