Reputation: 539
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 ?
Upvotes: 2
Views: 1314
Reputation: 3389
Because $item
is not a reference of $newarray[$loop_index]
:
foreach($newarray as $loop_index => $item){
$newarray[$loop_index]["total"] = 9;
}
Upvotes: 3
Reputation: 6683
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.
Upvotes: 1