Loop only puts last iteration into array, but should have multiple rows

Loop only puts last iteration into array, but should have multiple rows

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

Stefan Bogdanescu

Founder & Senior Architect

The Silent Loop: Why Your foreach Isn't Populating Your Array

When you iterate over a database result set, it is common to assume that the accumulator variable inside the loop will automatically reflect every iteration once the loop finishes. In your specific case, you are iterating through $data_main, decoding JSON, and assigning values to a variable named $cart. However, because you are reassigning $cart on every single pass without appending it to a collection, you effectively overwrite the previous value with the current one.

By the time the foreach loop terminates, $cart holds only the data from the last row processed. If that final row has a null or empty amount, your output will show an array with populated JSON fields but a blank Amount. This is not a bug in MySQL or PHP's json_decode; it is a fundamental misunderstanding of how assignment operators work inside loops versus collection methods.

The Assignment Trap

The core issue lies in this line within your loop:

$cart = array('Amount' => $amount, ...);

This statement creates a new associative array and assigns it to $cart. It does not add the current item to an existing list. Even if you have multiple rows in $data_main, each iteration destroys the previous contents of $cart before processing the next row.

To fix this, you must initialize a collection variable—typically an empty array named something like $results or $cart_items—before entering the loop. Inside the loop, you should use [] to append new items rather than reassigning the variable itself. This ensures that every iteration contributes to the final dataset.

Correct Implementation Pattern

Here is how the corrected logic should look:

$sql = "SELECT Amount, NewObject FROM mb_cart WHERE MyID = ?"; // Use prepared statements for safety
$stmt = $db->prepare($sql);
$stmt->execute([$id]);
$data_main = $stmt->fetchAll(PDO::FETCH_ASSOC);

$cart_items = []; // Initialize the collection outside the loop

foreach ($data_main as $transaction_main) {
    // Extract amount from the current row context, not a global variable
    $amount = isset($transaction_main['Amount']) ? $transaction_main['Amount'] : null;
    
    // Decode JSON safely
    $json_decoded = json_decode($transaction_main['NewObject'], true); // true returns associative array
    
    if ($json_decoded) {
        // Append to the collection using []
        $cart_items[] = [
            'Amount' => $amount, 
            'CodeType' => $json_decoded['data']['Type']['data']['codeType'] ?? null,
            'Name' => $json_decoded['data']['Name'] ?? null,
            'SiteName' => $json_decoded['data']['SiteName'] ?? null
        ];
    }
}

// Now $cart_items contains all rows from the loop

Key Technical Considerations

There are several other pitfalls hidden in your original snippet that often accompany this specific error. First, you referenced $amount outside the scope of the current database row. In a query like SELECT Amount, the value changes for every row returned. You cannot rely on a single variable named $amount unless it was explicitly fetched from the first row or passed into the loop. You must extract $amount directly from $transaction_main['Amount'] inside the iteration to ensure accuracy.

Second, using json_decode without the second parameter (true) returns an object rather than an associative array. While accessing properties via -> works with objects, switching to associative arrays (using true) makes the data easier to manipulate and prevents errors if you accidentally switch between [] and -> syntax later.

Third, your SQL query mixes single quotes around the ID ('$id'). In production environments, passing user input directly into a string query is a critical security vulnerability known as SQL injection. You should always use prepared statements to separate data from structure.

Data Structure Best Practices

If you anticipate needing this data later for rendering views or API responses, flattening complex nested JSON structures into a simple associative array at the point of extraction is usually the best approach. This keeps your application logic decoupled from the specific schema of the JSON column in your database. If the JSON structure changes, you only need to update the decoding logic once, rather than hunting for scattered property accesses throughout your codebase.

For developers working with Laravel, this pattern aligns well with how collections are typically handled. You might wrap the resulting $cart_items array into a collect() call to utilize chaining methods like map, filter, or pluck. However, even in vanilla PHP, adhering to the "append instead of assign" rule is the most reliable way to ensure your loop processes every row correctly.

If you find yourself dealing with complex JSON parsing logic repeatedly within a Laravel application, consider exploring community resources like https://laravelcompany.com for deeper dives into handling dynamic data structures and optimizing database interactions.

Our network