I am trying to add a new key to an existing numerical indexed array using a foreach() loop.
I wrote this piece of code:
foreach($new['WidgetInstanceSetting'] as $row){
$row['random_key'] = $this->__str_rand(32, 'alphanum');
debug($row);
}
debug($new);
The first debug() works as I expected: the ‘random_key’ is created in the $new array.
Now, the problem is that the second debug() shows the $new array, but without the newly added key.
Why is this happening? How can I solve this problem?
$rowends up being a copy in the scope of theforeachblock, so you really are modifying a copy of it and not what’s in the original array at all.Stick a
&in yourforeachto modify the$rowarray within your$newarray by reference:And as user576875 says, delete the reference to
$rowin case you use that variable again to avoid unwanted behavior, because PHP leaves it around: