Search code examples
phplaravellaravel-collection

Laravel Collection update elements in loop


I declared a variable of collect() data type. I want to iterate through it, and to update specific column on each row.

The example code:

    $a = collect([
        ['one' => 1, 'two' => 2],
        ['one' => 3, 'two' => 4],
        ['one' => 5, 'two' => 6]
    ]);

    foreach ($a as $b) {
        $b['one'] = 0;
    }

    dd($a);

I don't understand, why the result is this:


Collection {#510 ▼
  #items: array:3 [▼
    0 => array:2 [▼
      "one" => 1
      "two" => 2
    ]
    1 => array:2 [▼
      "one" => 3
      "two" => 4
    ]
    2 => array:2 [▼
      "one" => 5
      "two" => 6
    ]
  ]
}

I expect "one" => 0 as a result for each row.


Solution

  • You are not modifying the original array, there is no place where you store the modified item back to the array. For this purpose it is better to use the map function on the collection itself.

    $a = collect([['one' => 1, 'two' => 2], ['one' => 3, 'two' => 4], ['one' => 5, 'two' => 6]]);
    
    $a = $a->map(function($item) { 
        $item['one'] = 0; 
        return $item; 
    });
    

    The for each way:

    foreach ($a as $key => $b) {
       $b['one'] = 0;
       $a[$key] = $b; // override the original item.
    }