If I have an array like this:
array(2) {
[0]=>
array(2) {
["id"]=>
string(2) "34"
["total"]=>
string(6) "122337"
},
[1]=>
array(2) {
["id"]=>
string(2) "43"
["total"]=>
string(6) "232337"
}
}
And I want to add a new key value to each sub array, so for example, it would end like this:
array(2) {
[0]=>
array(2) {
["id"]=>
string(2) "34"
["total"]=>
string(6) "122337"
["newkey"]=>
string(6) "hihihi"
},
[1]=>
array(2) {
["id"]=>
string(2) "43"
["total"]=>
string(6) "232337"
["newkey"]=>
string(6) "hihihi"
}
}
How would I do it?
I have tried with a foreach like this:
foreach($exterior_array as $inside_array) {
$inside_array['newkey'] = "hihihi";
}
But once I get inside the foreach, the values are not saved.
That is because you are working on a copy of the array via
$inside_array. You can access the “orignal” value you want to change by making$inside_arrayan alias of the origina value; using a reference:Compare with http://php.net/foreach