Adding arrays to multi-dimensional array within loop

Adding arrays to multi-dimensional array within loop

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

The Trap of array_merge in PHP Loops

You are encountering a classic PHP pitfall when trying to build a multi-dimensional array inside a loop using array_merge. The issue isn't that the merge operation itself is broken; rather, it stems from how array_merge handles keys. When you use numeric indices (like 0, 1, 2), array_merge re-indexes those keys sequentially.

In your specific case, every iteration of your loop creates a new sub-array with keys: 'player_id', 'goals', 'player_num', and 'fixture_id'. Because these are all strings (associative keys), array_merge treats them as associative arrays. However, the real problem arises if you were using numeric indices or if the structure implies a list of rows where order matters without explicit keys.

Wait, looking closer at your code snippet:

$allplayerdata = array(
    'player_id' => $this->input->post('player' . $i),
    'goals' => $this->input->post('playergoals' . $i),
    'player_num' => $i,
    'fixture_id' => $this->input->post('fixture_id')
);

$allplayerdata = array_merge($allplayerdata, $playerdata);

The keys here are strings. array_merge should theoretically preserve them. So why does print_r show only the last sub-array?

The culprit is likely an invisible newline character or a misunderstanding of how array_merge behaves with mixed structures, but there is a more fundamental logical error in how you are accumulating data if the result looks like a flat list instead of a nested one. Actually, array_merge on two arrays where the second has the same string keys as the first will overwrite the values in the destination array for every key present in both.

If $allplayerdata is initially empty, and you merge $playerdata (which has 4 keys) into it, $allplayerdata becomes identical to $playerdata. In the next iteration, you merge another $playerdata (with the same 4 keys) into $allplayerdata. Because the keys match exactly, the values from the new $playerdata overwrite the existing values in $allplayerdata. You are not appending; you are replacing.

To fix this, you need to ensure that each new row is added to a distinct index within the main container array, rather than merging flat structures with identical keys. The standard pattern for building a multi-dimensional array in PHP is to use [] (short syntax) or array_push, but strictly speaking, direct assignment to a dynamic key is the most explicit way to avoid re-indexing issues.

The Correct Approach: Direct Assignment

Instead of merging, you should append the new sub-array to the end of $allplayerdata. This preserves the structure where each element is a distinct row index (0, 1, 2...).

Here is the corrected implementation:

$allplayerdata = []; // Initialize empty array

for ($i = 1; $i <= 11; $i++) {
    $row = [
        'player_id' => $this->input->post('player' . $i),
        'goals'     => $this->input->post('playergoals' . $i),
        'player_num'=> $i,
        'fixture_id'=> $this->input->post('fixture_id')
    ];

    // Append the new row to the end of the main array
    $allplayerdata[] = $row; 
}

By using $allplayerdata[] = $row, PHP automatically assigns the next available integer index (0, then 1, then 2, etc.). This ensures that every iteration adds a new element to the list without overwriting previous keys. When you pass this structure to CodeIgniter's batch_insert or Laravel's insertBatches, it expects exactly this format: an array of arrays, where each inner array represents a row with identical column names.

Why array_merge Fails Here

It is important to understand why array_merge is unsuitable for accumulating rows in this specific context. array_merge is designed to combine two arrays into one, often used when you want to merge configuration settings or concatenate lists where keys don't collide. However, when keys are identical strings (like 'player_id'), array_merge replaces the value of the destination key with the source key's value.

If your code were slightly different and involved numeric indices, array_merge would re-index them as 0, 1, 2, potentially losing data if you relied on specific positions. With associative keys, it acts as a replacement mechanism rather than an accumulation one. This behavior is consistent across PHP versions, though some edge cases with resources (like file handles) might behave differently in older versions; for standard data structures, the replacement logic stands.

Alternative: Collecting First, Then Inserting

Another common pattern, often seen when using frameworks like Laravel, is to collect all the data first and then perform the batch insert in a separate step. This separates the data gathering logic from the persistence logic, making it easier to debug or add validation later.

If you are working within a Laravel context specifically, you might prefer using collect() with push for readability:

$allplayerdata = collect()->map(function($i) {
    return [
        'player_id' => $this->input->post('player' . $i),
        'goals'     => $this->input->post('playergoals' . $i),
        'player_num'=> $i,
        'fixture_id'=> $this->input->post('fixture_id')
    ];
});

However, the iterative [] approach remains the most efficient for simple loops and aligns perfectly with what CodeIgniter's batch_insert expects. The key takeaway is to treat your main container array as a list of distinct items, not a bag of keys to be merged repeatedly.

Our network