0

So $tr['tree'] is an array. $dic is an array stored as key values. I want to add the key source to that those arrays. It looks like the following code doesn't work as expected as I'm guessing $dic is a new instance of the array object inside $tr['tree'].

foreach($tr['tree'] as $dic){
    $dic['source'] = $tr['source']." > ".$dic['name'];
}

Note, I'm coming from python where this would work brilliantly. So how would I do this in PHP?

Jonathan
  • 8,453
  • 9
  • 51
  • 74
  • 1
    Add an ampersand to tell php you that it should loop by reference, e.g. `foreach($tr['tree'] as &$dic)`. Here is your startpoint: http://php.net/manual/en/language.references.php – Rizier123 May 15 '15 at 15:14
  • Add that as an answer and I'll upvote it and accept it :) – Jonathan May 15 '15 at 15:16
  • I think this is a pretty good one: http://stackoverflow.com/a/30263129/ – Rizier123 May 15 '15 at 15:18

1 Answers1

4

foreach() creates copies of the items you're looping on, so $dic in the loop is detached from the array. If you want to modify the parent array, the safe method is to use:

foreach($array as $key => $value) {
   $array[$key] = $new_value;
}

You could use a reference:

foreach($array as &$value) {
                  ^---
     $value = $new_value;
}

but that can lead to stupidly-hard-to-find bugs later. $value will REMAIN a reference after the foreach terminates. If you re-use that variable name later on for other stuff, you'll be modifying the array, because the var still points at it.

Marc B
  • 356,200
  • 43
  • 426
  • 500
  • For the strange behaviour: http://stackoverflow.com/q/4969243 this is a good example. (And if you would want to go "deeper" how it works with `is_ref` and so on: http://stackoverflow.com/q/10057671) (<- If you want take it in your answer as examples/references) – Rizier123 May 15 '15 at 15:20
  • In the example I gave I needed to modify the child array. What would a safe way be there? – Jonathan May 15 '15 at 15:20
  • `$array[$key][$childkey]`... since you're dealing with the original array for the assignment, doesn't matter how/what you do inside the loop - you'd be modifying the "real" data. of course, if you start doing silly things like adding/removing things in `$array` itself, then the you start entering undefined territory – Marc B May 15 '15 at 15:22
  • @MarcB Not necessarily *undefined* -> http://stackoverflow.com/a/14854568/3933332 you just have to know what PHP does – Rizier123 May 15 '15 at 15:23