DEV Community

Cover image for Using array_merge in a PHP loop is considered bad practice
Maico Orazio
Maico Orazio

Posted on

Using array_merge in a PHP loop is considered bad practice

To use the array_merge function in a for / foreach / while loop, do the following:

$arraysToMerge = [ [1, 2], [2, 3], [5, 8] ];

$arraysMerged = [];
foreach($arraysToMerge as $array) {
    $arraysMerged = array_merge($arraysMerged, $array);
}
Enter fullscreen mode Exit fullscreen mode

is a poor practice 😱 because it is a performance drain (especially on memory).

Since PHP 5.6, there is a new operator, the spread operator,

$arraysToMerge = [ [1, 2], [2, 3], [5,8] ];

$arraysMerged = array_merge([], ...$arraysToMerge);
print_r($arraysMerged);
Enter fullscreen mode Exit fullscreen mode

output

Array
(
    [0] => 1
    [1] => 2
    [2] => 2
    [3] => 3
    [4] => 5
    [5] => 8
)
Enter fullscreen mode Exit fullscreen mode

which automatically expands the array without the need to loop through it.

  • No more performance issues
  • No for / foreach / while loops
  • Processed in a single line of code.

A more complex example can be represented by the following case:

  • I have a list of students
  • For each of them, I need to retrieve their used books
  • I need to store them in a new array structure

It is possible to use the spread operator, but an intermediate process is required:

// student data model
$students = [['id'=>1],['id'=>2],['id'=>3]];

// retrieve used books by student ID
function searchUsedBooksByStudent($id) {
    $books = [];
    $books[1] = ['italian', 'history'];
    $books[2] = ['mathematics'];
    $books[3] = ['latin'];
    if (isset($books[$id])) {
        return $books[$id];
    }
    return [];
}


$arrayUsedBooks = [];
foreach ($students as $student) {
    $books = searchUsedBooksByStudent($student['id']);
    if ($books) {
      $arrayUsedBooks[] = $books;
    }
}
$arraysMerged = array_merge([], ...$arrayUsedBooks);
print_r($arraysMerged);
Enter fullscreen mode Exit fullscreen mode

output

 Array
(
    [0] => italian
    [1] => history
    [2] => mathematics
    [3] => latin
)
Enter fullscreen mode Exit fullscreen mode

I hope these examples are helpful. Now, look at your code to see what you can improve!

Good work 👨‍💻

Top comments (0)