2

I have an array of arrays, and I am trying to foreach loop through and insert new item into the sub arrays.

take a look below

            $newarray = array(
                    array("id"=>1,"quantity"=>2),
                    array("id"=>1,"quantity"=>2),
                    array("id"=>1,"quantity"=>2),
           );

           foreach($newarray as $item){
                $item["total"] = 9;
            }
           echo "<br>";
           print_r($newarray);

The result just give me the original array without the new "total". Why ?

codenoob
  • 539
  • 1
  • 9
  • 26
  • http://stackoverflow.com/questions/16491704/php-insert-value-into-array-of-arrays-using-foreach – sumit Feb 19 '17 at 20:18

2 Answers2

3

Because $item is not a reference of $newarray[$loop_index]:

foreach($newarray as $loop_index => $item){
    $newarray[$loop_index]["total"] = 9;
}
Eduardo Escobar
  • 3,301
  • 2
  • 18
  • 15
1

The foreach() statement gives $item as an array: Not as the real value (consuming array). That meaning it can be read but not changed unless you then overwrite the consuming array.

You could use the for() and loop through like this: see demo.

Note: This goes all the way back to scopes, you should look into that.

Jaquarh
  • 6,493
  • 7
  • 34
  • 86