DEV Community

spO0q
spO0q

Posted on • Edited on

Spread it!

I'm usually not a big fan of "1-line refactoring", as it often means less readable code and clever syntaxes that only make maintenance more time-consuming.

Of course, it's not always the case, and, for example, in PHP, I like to refactor the following code:

$letters = [ ["a","b",], ["c","d",], ["e","f",], ["g","h"], ["i","j"] ];
$tmp = [];
foreach ($letters as $row) {
    $tmp = array_merge($tmp, $row);
}
print_r($tmp);
Enter fullscreen mode Exit fullscreen mode

to this one:

$letters = array_merge(...$letters);
Enter fullscreen mode Exit fullscreen mode

It uses the spread operator and removes the hassle of useless temporary arrays. Besides, the first one can be a bad practice in terms of performance, because you use array_merge inside a loop.

Top comments (0)