JesusValera

Avoid using array_merge within a loop

 Found a typo? Edit me

salto-del-usero-bullas

If you're a PHP developer, chances are you've encountered (or written) code like this:

$userLists = [];
foreach ($this->someCall() as $someObject) {
    $userLists = array_merge($userLists, $someObject->getUsers());
}

The goal here is to populate the $userLists array with users returned from some external source (in this case, from $someObject->getUsers()). An instinct is to use array_merge inside the loop to combine arrays.

While this works, there's a performance caveat: array_merge creates a new array every time it's called, duplicating all elements and discarding the previous one. This approach may be fine for small arrays, but the cost grows significantly with larger datasets.

Alternatives for better performance

Spread operator (merge once at the end)

Instead of merging in every iteration, we collect all elements and merge them only once at the end.

$userLists = [];
foreach ($this->someCall() as $someObject) {
    $userLists[] = $someObject->getUsers();
}
$userLists = array_merge(...$userLists);

Pros and cons:

Manual nested loop

This method avoids all intermediate arrays and merges on the fly.

$userLists = [];
foreach ($this->someCall() as $someObject) {
    foreach ($someObject->getUsers() as $user) {
        $userLists[] = $user;
    }
}

Pros and cons: